Sending email

suggest change

Ruby can send email without any gems: Net::SMTP speaks the SMTP protocol to a mail server. It only moves bytes, though. You have to build the message yourself, including headers, encodings and MIME parts. The mail gem does that part: it builds correct multipart messages with attachments and non-ASCII text, and it also delivers them over SMTP (using Net::SMTP underneath), to files, or to an in-memory list for tests. Rails' Action Mailer is built on top of mail.

This article covers both libraries: plain-text messages, TLS and authentication, multiple recipients and Bcc, errors, HTML email with attachments, sending many messages over one connection, and testing.

The examples were run with Ruby 4.0, net-smtp 0.5 and mail 2.9. net-smtp is a bundled gem, so it comes with Ruby. In a Bundler project add gem 'net-smtp' to the Gemfile anyway. Install mail with gem install mail.

A local SMTP server to experiment with

Don't test against a real mail server: you'll spam real people, or end up on a block list. Use a server that accepts everything and delivers nothing. Tools like Mailpit or MailHog do this and show the messages in a web UI. For the examples below we use a small sink written in Ruby that prints each message it receives. Port 2525 is plain SMTP. Port 2526 also offers STARTTLS with a self-signed certificate. The sink saves the certificate to sink-cert.pem so clients can trust it. It accepts the login alice / secret and rejects any address at invalid.example:

# smtp_sink.rb - a local SMTP server that prints messages instead of delivering them
require 'socket'
require 'openssl'

PORT  = Integer(ENV.fetch('PORT', 2525))
USERS = { 'alice' => 'secret' }.freeze

# A self-signed certificate for STARTTLS, also saved so clients can trust it
KEY  = OpenSSL::PKey::RSA.new(2048)
CERT = OpenSSL::X509::Certificate.new.tap do |c|
  c.version    = 2
  c.serial     = 1
  c.subject    = c.issuer = OpenSSL::X509::Name.parse('/CN=localhost')
  c.public_key = KEY
  c.not_before = Time.now - 60
  c.not_after  = Time.now + 86_400
  ef = OpenSSL::X509::ExtensionFactory.new(c, c)
  c.add_extension(ef.create_extension('subjectAltName', 'DNS:localhost,IP:127.0.0.1'))
  c.add_extension(ef.create_extension('basicConstraints', 'CA:TRUE', true))
  c.sign(KEY, OpenSSL::Digest.new('SHA256'))
end
File.write('sink-cert.pem', CERT.to_pem)

def session(sock, offer_tls)
  say = ->(line) { sock.write("#{line}\r\n") }
  user = from = nil
  rcpts = []
  tls = false
  say.("220 localhost test sink ready")
  while (line = sock.gets)
    cmd, arg = line.chomp.split(' ', 2)
    case cmd.to_s.upcase
    when 'EHLO'
      say.("250-localhost greets #{arg}")
      say.("250-SIZE 10485760")
      say.("250-8BITMIME")
      say.("250-STARTTLS") if offer_tls && !tls
      say.("250 AUTH PLAIN LOGIN")
    when 'HELO' then say.("250 localhost")
    when 'STARTTLS'
      say.("220 go ahead")
      ctx = OpenSSL::SSL::SSLContext.new
      ctx.cert, ctx.key = CERT, KEY
      sock = OpenSSL::SSL::SSLSocket.new(sock, ctx).tap(&:accept)
      tls = true
    when 'AUTH'
      mech, initial = arg.to_s.split(' ', 2)
      name, pass =
        if mech.upcase == 'PLAIN'
          initial.unpack1('m').split("\0")[1, 2]
        else # LOGIN
          say.("334 VXNlcm5hbWU6") # "Username:"
          n = sock.gets.unpack1('m')
          say.("334 UGFzc3dvcmQ6") # "Password:"
          [n, sock.gets.unpack1('m')]
        end
      if USERS[name] == pass
        user = name
        say.("235 2.7.0 Authentication successful")
      else
        say.("535 5.7.8 Authentication credentials invalid")
      end
    when 'MAIL'
      from = arg[/<(.*)>/, 1]
      rcpts = []
      say.("250 2.1.0 OK")
    when 'RCPT'
      to = arg[/<(.*)>/, 1]
      if to.end_with?('@invalid.example')
        say.("550 5.1.1 No such user: #{to}")
      else
        rcpts << to
        say.("250 2.1.5 OK")
      end
    when 'DATA'
      say.("354 End data with <CR><LF>.<CR><LF>")
      data = +''
      while (l = sock.gets) && l != ".\r\n"
        data << (l.start_with?('..') ? l[1..] : l)
      end
      puts "=== from=#{from} to=#{rcpts.join(',')} tls=#{tls} auth=#{user.inspect} " \
           "bytes=#{data.bytesize}", data.gsub("\r\n", "\n"), '=== end', ''
      $stdout.flush
      say.("250 2.0.0 OK queued")
    when 'RSET' then from = nil; rcpts = []; say.("250 OK")
    when 'NOOP' then say.("250 OK")
    when 'QUIT' then say.("221 Bye"); break
    else say.("502 Command not implemented")
    end
  end
rescue => e
  warn "session error: #{e.class}: #{e.message}"
ensure
  sock.close
end

# Port 2525: plain SMTP. Port 2526: also offers STARTTLS.
[[PORT, false], [PORT + 1, true]].each do |port, offer_tls|
  server = TCPServer.new('127.0.0.1', port)
  Thread.new { loop { Thread.new(server.accept) { |s| session(s, offer_tls) } } }
end
puts "SMTP sink on 127.0.0.1:#{PORT} (plain) and :#{PORT + 1} (STARTTLS)"
$stdout.flush
sleep

Start it with ruby smtp_sink.rb in one terminal, then run the examples in another terminal from the same directory. The sink also shows the shape of SMTP. The client says EHLO, can upgrade the connection with STARTTLS and log in with AUTH, then sends the envelope (MAIL FROM, one RCPT TO per recipient) and finally the message itself after DATA. For more on servers like this see TCP sockets.

Sending a message with Net::SMTP

A message is text: header lines, an empty line, then the body. Net::SMTP.start opens a connection, yields it, and closes it at the end of the block. send_message takes the message, the envelope sender, and one or more envelope recipients:

require 'net/smtp'

message = <<~MSG
  From: Alice <alice@example.com>
  To: Bob <bob@example.com>
  Subject: Hello from Ruby
  Date: #{Time.now.strftime('%a, %d %b %Y %H:%M:%S %z')}
  Message-ID: <#{Time.now.to_i}.#{rand(1_000_000)}@example.com>

  Hi Bob,

  This message was sent with Net::SMTP.
MSG

Net::SMTP.start('localhost', 2525) do |smtp|
  res = smtp.send_message(message, 'alice@example.com', 'bob@example.com')
  p res
  puts res.status, res.string
end
#<Net::SMTP::Response:0x0000019816e60190 @status="250", @string="250 2.0.0 OK queued\n">
250
250 2.0.0 OK queued

The sink received:

=== from=alice@example.com to=bob@example.com tls=false auth=nil bytes=222
From: Alice <alice@example.com>
To: Bob <bob@example.com>
Subject: Hello from Ruby
Date: Sat, 17 Oct 2026 22:42:12 +0200
Message-ID: <1792269732.446813@example.com>

Hi Bob,

This message was sent with Net::SMTP.
=== end

A few things to know:

STARTTLS and authentication

Real mail providers want an encrypted connection and a login. There are two ways to encrypt:

The default is starttls: :auto, which upgrades only if the server offers STARTTLS. Someone who can tamper with the connection can remove that offer, and then your password goes out in plain text. Use :always when you send credentials. Pass credentials to start with user: and secret::

require 'net/smtp'

message = <<~MSG
  From: alice@example.com
  To: bob@example.com
  Subject: Over TLS

  Encrypted and authenticated.
MSG

smtp = Net::SMTP.new('localhost', 2526,
                     starttls: :always,
                     ssl_context_params: { ca_file: 'sink-cert.pem' })
smtp.open_timeout = 5
smtp.read_timeout = 10

smtp.start(helo: 'myapp.example.com', user: 'alice', secret: 'secret', authtype: :plain) do |s|
  puts "TLS: #{s.starttls_always?}, capable auth: #{s.capable_auth_types.inspect}"
  s.send_message(message, 'alice@example.com', 'bob@example.com')
end
puts 'sent'
TLS: true, capable auth: ["PLAIN", "LOGIN"]
sent
=== from=alice@example.com to=bob@example.com tls=true auth="alice" bytes=97
From: alice@example.com
To: bob@example.com
Subject: Over TLS

Encrypted and authenticated.
=== end

Notes:

Each of these mistakes raises a specific exception:

require 'net/smtp'

# 1. The server's certificate isn't trusted
begin
  Net::SMTP.start('localhost', 2526, starttls: :always) { }
rescue OpenSSL::SSL::SSLError => e
  puts "#{e.class}: #{e.message}"
end

# 2. Wrong password
begin
  Net::SMTP.start('localhost', 2526, user: 'alice', secret: 'wrong',
                  ssl_context_params: { ca_file: 'sink-cert.pem' }) { }
rescue Net::SMTPAuthenticationError => e
  puts "#{e.class}: #{e.message}"
end

# 3. Credentials but no TLS: refuse to send them in clear text
begin
  Net::SMTP.start('localhost', 2525, user: 'alice', secret: 'secret',
                  starttls: :always) { }
rescue Net::SMTPUnsupportedCommand => e
  puts "#{e.class}: #{e.message}"
end
OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 peeraddr=127.0.0.1:2526 state=error: certificate verify failed (self-signed certificate)
Net::SMTPAuthenticationError: 535 5.7.8 Authentication credentials invalid
Net::SMTPUnsupportedCommand: STARTTLS is not supported on this server

When certificate verification fails, fix the trust (ca_file:) or the hostname (tls_hostname:). Don't set verify_mode: OpenSSL::SSL::VERIFY_NONE, because that makes TLS useless against an attacker in the middle.

Several recipients, Bcc, and many messages

Pass several envelope recipients to send one message to all of them. A Bcc recipient is an address that is in the envelope but not in any header. To send many different messages, reuse one connection instead of opening a new one for each:

require 'net/smtp'

users = { 'bob@example.com' => 'Bob', 'carol@example.com' => 'Carol' }

# One connection, many messages
Net::SMTP.start('localhost', 2525) do |smtp|
  users.each do |email, name|
    smtp.send_message(<<~MSG, 'news@example.com', email)
      From: news@example.com
      To: #{name} <#{email}>
      Subject: Weekly news

      Hi #{name}!
    MSG
    puts "sent to #{email}"
  end

  # One message, several recipients; dave is a Bcc: he's in the
  # envelope (who receives it) but not in the headers (what is shown)
  smtp.send_message(<<~MSG, 'alice@example.com', 'bob@example.com', 'carol@example.com', 'dave@example.com')
    From: alice@example.com
    To: bob@example.com, carol@example.com
    Subject: Team lunch

    Friday at noon?
  MSG
end
sent to bob@example.com
sent to carol@example.com

The last message arrives as:

=== from=alice@example.com to=bob@example.com,carol@example.com,dave@example.com tls=false auth=nil bytes=105
From: alice@example.com
To: bob@example.com, carol@example.com
Subject: Team lunch

Friday at noon?
=== end

Errors

SMTP replies have three-digit codes. 2xx means success. 4xx is a temporary failure (server busy, mailbox full, greylisting) and is worth retrying later. 5xx is permanent (no such user, message rejected), so don't retry it. Net::SMTP raises a different exception class for each kind:

require 'net/smtp'

msg = "From: alice@example.com\nTo: nobody@invalid.example\nSubject: Hi\n\nHello\n"

begin
  Net::SMTP.start('localhost', 2525) do |smtp|
    smtp.send_message(msg, 'alice@example.com', 'nobody@invalid.example')
  end
rescue Net::SMTPFatalError => e      # 5xx: permanent, don't retry
  puts "#{e.class}: #{e.message.strip}"
  p e.response.status
end

begin
  Net::SMTP.start('localhost', 1) { }  # nothing listens on port 1
rescue Errno::ECONNREFUSED => e
  puts "#{e.class}: #{e.message}"
end

p Net::SMTPFatalError.ancestors.take_while { _1 != StandardError }
p Net::SMTPServerBusy.ancestors.take_while { _1 != StandardError }
Net::SMTPFatalError: 550 5.1.1 No such user: nobody@invalid.example
"550"
Errno::ECONNREFUSED: No connection could be made because the target machine actively refused it. - connect(2) for "localhost" port 1
[Net::SMTPFatalError, Net::SMTPError, Net::ProtoFatalError, Net::ProtocolError]
[Net::SMTPServerBusy, Net::SMTPError, Net::ProtoServerError, Net::ProtocolError]

(The ECONNREFUSED text comes from the OS. On Linux and macOS it reads "Connection refused".)

Exception Meaning Retry?
Net::SMTPServerBusy 4xx temporary failure yes, with backoff
Net::SMTPFatalError 5xx permanent failure no
Net::SMTPAuthenticationError bad credentials (535) no, fix the config
Net::SMTPSyntaxError the server didn't understand a command no
Net::OpenTimeout, Net::ReadTimeout, Errno::ECONNREFUSED, Errno::ECONNRESET network problems yes

rescue Net::SMTPError catches all the protocol errors. If one recipient of a multi-recipient message is rejected, the whole send_message call fails and nobody gets the message. For retry loops see Retrying.

Even a 250 reply only means that this server accepted the message. A bounce can still arrive later, as an email to the envelope sender. That's why the envelope sender is often a dedicated bounce address.

Building messages with the mail gem

Mail.new takes a block, or a Hash, of header fields and the body. It adds Date, Message-ID, MIME-Version and Content-Type for you:

require 'mail'

mail = Mail.new do
  from    'Alice <alice@example.com>'
  to      ['bob@example.com', 'Carol <carol@example.com>']
  subject 'Hello from the mail gem'
  body    "Hi!\n\nThis one was built with Mail.new.\n"
end

puts mail.to_s
p mail.to
p mail[:from].display_names
Date: Sat, 17 Oct 2026 22:43:23 +0200
From: Alice <alice@example.com>
To: bob@example.com, 
 Carol <carol@example.com>
Message-ID: <6ad3ddeba9e4e_2124100-58e@myhost.mail>
Subject: Hello from the mail gem
MIME-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

Hi!

This one was built with Mail.new.
["bob@example.com", "carol@example.com"]
["Alice"]

mail.to returns plain addresses, so you can use it as the envelope. Long headers are folded onto continuation lines that start with a space, which is valid email syntax.

HTML email with attachments over SMTP

Configure delivery once with Mail.defaults. The SMTP options mirror Net::SMTP's. A good email has a plain-text version and an HTML version of the same content inside a multipart/alternative part, and the mail program shows the best one it can. Attachments go next to that part, inside multipart/mixed:

require 'mail'

Mail.defaults do
  delivery_method :smtp,
                  address: 'localhost',
                  port: 2526,
                  domain: 'myapp.example.com',      # sent in EHLO
                  user_name: 'alice',               # ENV['SMTP_USER'] in real code
                  password: 'secret',               # ENV['SMTP_PASSWORD']
                  authentication: :plain,
                  enable_starttls: :always,
                  ca_file: 'sink-cert.pem',         # trust our test server's certificate
                  open_timeout: 5,
                  read_timeout: 10
end

mail = Mail.new do
  from     'Shop <orders@example.com>'
  to       'Zoë Müller <zoe@example.com>'
  reply_to 'support@example.com'
  subject  'Your order #1042 — thank you!'

  # text and HTML versions of the same content...
  part content_type: 'multipart/alternative' do |alt|
    alt.text_part do
      content_type 'text/plain; charset=UTF-8'
      body "Hi Zoë,\n\nYour order has shipped.\n"
    end
    alt.html_part do
      content_type 'text/html; charset=UTF-8'
      body '<p>Hi Zoë,</p><p>Your order has <b>shipped</b>.</p>'
    end
  end

  # ...plus an attachment
  add_file 'report.csv'
end

mail.deliver!
puts "delivered #{mail.message_id}"
delivered 6ad3de0e5727e_780c100-2f4@myhost.mail

The sink shows the structure. Non-ASCII headers are encoded as RFC 2047 words (=?UTF-8?...?=), non-ASCII bodies as quoted-printable, and the attachment as base64:

=== from=orders@example.com to=zoe@example.com tls=true auth="alice" bytes=1286
Date: Sat, 17 Oct 2026 22:43:58 +0200
From: Shop <orders@example.com>
Reply-To: support@example.com
To: =?UTF-8?B?Wm/DqyBNw7xsbGVy?= <zoe@example.com>
Message-ID: <6ad3de0e5727e_780c100-2f4@myhost.mail>
Subject: =?UTF-8?Q?Your_order_#1042_=E2=80=94_thank_you!?=
MIME-Version: 1.0
Content-Type: multipart/mixed;
 boundary="--==_mimepart_6ad3de0c1a8e8_780c100-334"
Content-Transfer-Encoding: 7bit


----==_mimepart_6ad3de0c1a8e8_780c100-334
Content-Type: multipart/alternative;
 boundary="--==_mimepart_6ad3de0c1a859_780c100-49b"
Content-Transfer-Encoding: 7bit


----==_mimepart_6ad3de0c1a859_780c100-49b
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: quoted-printable

Hi Zo=C3=AB,

Your order has shipped.

----==_mimepart_6ad3de0c1a859_780c100-49b
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<p>Hi Zo=C3=AB,</p><p>Your order has <b>shipped</b>.</p>=

----==_mimepart_6ad3de0c1a859_780c100-49b--

----==_mimepart_6ad3de0c1a8e8_780c100-334
Content-Type: text/csv;
 charset=UTF-8;
 filename=report.csv
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
 filename=report.csv

aWQsdG90YWwKMSw5Ljk5CjIsMjQuNTAK

----==_mimepart_6ad3de0c1a8e8_780c100-334--
=== end

Two gotchas:

For larger templates, render the text and HTML bodies with ERB.

Attachments from memory and Bcc

attachments['name'] = ... attaches data you already have in memory. The MIME type is guessed from the name, or you can set it with mime_type:. Mail.deliver builds and sends in one step. With mail, Bcc works the way you would expect: the address is added to the envelope and the Bcc: header is removed before sending:

require 'mail'

Mail.defaults { delivery_method :smtp, address: 'localhost', port: 2525 }

mail = Mail.deliver do
  from    'alice@example.com'
  to      'bob@example.com'
  bcc     'audit@example.com'
  subject 'Quarterly numbers'
  text_part { body 'See you at the meeting.' }
  attachments['numbers.json'] = { mime_type: 'application/json', content: '{"q3": 1234}' }
end

p mail.destinations          # envelope recipients
p mail.attachments.map(&:filename)
["bob@example.com", "audit@example.com"]
["numbers.json"]
=== from=alice@example.com to=bob@example.com,audit@example.com tls=false auth=nil bytes=697
Date: Sat, 17 Oct 2026 22:44:17 +0200
From: alice@example.com
To: bob@example.com
Message-ID: <6ad3de21c2613_6860100-384@myhost.mail>
Subject: Quarterly numbers
MIME-Version: 1.0
Content-Type: multipart/mixed;
 boundary="--==_mimepart_6ad3de1fa6acb_6860100-4a2"
Content-Transfer-Encoding: 7bit


----==_mimepart_6ad3de1fa6acb_6860100-4a2
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

See you at the meeting.
----==_mimepart_6ad3de1fa6acb_6860100-4a2
Content-Type: application/json
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
 filename=numbers.json

eyJxMyI6IDEyMzR9

----==_mimepart_6ad3de1fa6acb_6860100-4a2--
=== end

Use text_part rather than body when the message has attachments. If you write body 'See you at the meeting.' in the block above, the message is sent with only the attachment and the text is silently lost.

Many messages over one connection

Mail.deliver opens a new SMTP connection for every message. For a batch, open the connection yourself and hand it to Mail::SMTPConnection. After a failed recipient, call rset to cancel the half-finished transaction and keep using the connection:

require 'mail'
require 'net/smtp'

recipients = %w[bob@example.com carol@example.com nobody@invalid.example dave@example.com]

Net::SMTP.start('localhost', 2525) do |smtp|
  conn = Mail::SMTPConnection.new(connection: smtp)
  recipients.each do |email|
    mail = Mail.new(from: 'news@example.com', to: email,
                    subject: 'October newsletter', body: 'News!')
    begin
      conn.deliver!(mail)
      puts "ok     #{email}"
    rescue Net::SMTPFatalError => e
      puts "failed #{email}: #{e.message.strip}"
      smtp.rset                  # reset the transaction, keep the connection
    end
  end
end
ok     bob@example.com
ok     carol@example.com
failed nobody@invalid.example: 550 5.1.1 No such user: nobody@invalid.example
ok     dave@example.com

Providers limit how many messages you can send per connection and per minute. For large volumes, use the provider's batch API or a background job queue.

Streaming a large message

open_message_stream gives you an IO-like writer, so you can produce a big body piece by piece without building one giant String first:

require 'net/smtp'

Net::SMTP.start('localhost', 2525) do |smtp|
  smtp.open_message_stream('reports@example.com', 'bob@example.com') do |f|
    f.puts 'From: reports@example.com'
    f.puts 'To: bob@example.com'
    f.puts 'Subject: Daily report'
    f.puts
    3.times { |i| f.puts "line #{i + 1}" }   # e.g. rows from a database cursor
  end
end
=== from=reports@example.com to=bob@example.com tls=false auth=nil bytes=97
From: reports@example.com
To: bob@example.com
Subject: Daily report

line 1
line 2
line 3
=== end

Testing code that sends email

In tests you want to check the messages without any server. The :test delivery method keeps delivered messages in an Array:

require 'mail'

def send_welcome(email)
  Mail.deliver do
    from    'welcome@example.com'
    to      email
    subject 'Welcome!'
    body    "Thanks for signing up, #{email}."
  end
end

Mail.defaults { delivery_method :test }   # in your test setup

send_welcome('bob@example.com')
send_welcome('carol@example.com')

deliveries = Mail::TestMailer.deliveries
p deliveries.size
p deliveries.map(&:to)
p deliveries.last.subject
p deliveries.last.body.decoded

Mail::TestMailer.deliveries.clear          # between tests
p Mail::TestMailer.deliveries.size
2
[["bob@example.com"], ["carol@example.com"]]
"Welcome!"
"Thanks for signing up, carol@example.com."
0

During development, :file writes every message to a directory (one file per recipient) so you can open it:

require 'mail'

Mail.defaults { delivery_method :file, location: 'tmp/mails' }

Mail.deliver(from: 'a@example.com', to: ['bob@example.com', 'carol@example.com'],
             subject: 'Saved, not sent', body: 'Look in tmp/mails')

puts Dir['tmp/mails/*'].sort
tmp/mails/bob@example.com
tmp/mails/carol@example.com

Other delivery methods are :sendmail (pipes to the local sendmail binary), :exim and :logger. You can also pass your own class that responds to deliver!(mail), for example one that calls a provider's HTTP API.

Header injection

Never interpolate user input into a raw Net::SMTP message. A subject like "Hello\r\nBcc: victim@example.com" from a contact form would add a header, and your server would send spam for someone else. mail encodes line breaks in header values, so the input stays inside the subject:

require 'mail'

subject = "Hello\r\nBcc: victim@example.com"   # e.g. from a contact form
mail = Mail.new(from: 'a@example.com', to: 'b@example.com', subject: subject, body: 'x')
puts mail.header.to_s.lines.grep(/Subject|Bcc/)
p mail.bcc
Subject: Hello=0D=0ABcc: victim@example.com
nil

If you build messages by hand, reject any header value that contains \r or \n.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents