Send emails with SMTP in Ruby


SMTP in Ruby

Ruby developers have multiple options for sending emails using SMTP:

  • The net/http module from the standard library: The net/http module provides a light-weight and low-level solution for sending emails via SMTP. While it's useful for sending simple email messages, it can be too verbose if you're planning to send HTML emails with attachments and custom headers.
  • The Mail gem: Mail is an internet library for Ruby that is designed to handle email generation, parsing and sending in a simple, rubyesque manner. It's suitable for email-heavy applications that send complex emails with custom templates and (inline) attachments.
  • ActionMailer: ActionMailer is part of Ruby on Rails and is used for sending emails. It provides a way to make email sending simple and efficient. This should be your go-to choice if your application is developed using Ruby on Rails.

Prerequisites

Sending with the Ruby standard library

The net/smtp library is part of Ruby's standard library, offering a lower-level interface to send emails.

require 'net/smtp'

message = <<~MESSAGE_END
    From: Your Name 
    To: Recipient Name 
    Subject: SMTP Test Email
    Date: #{Time.now.rfc2822}

    This is a test email sent using net/smtp in Ruby.
MESSAGE_END

smtp_settings = {
    address: 'send.ahasend.com',
    port: 587,
    domain: 'domain.com', # your domain
    user_name: 'YOUR_SMTP_USERNAME',
    password: 'YOUR_SMTP_PASSWORD',
    authentication: 'plain',
    enable_starttls_auto: true
}

Net::SMTP.start(
    smtp_settings[:address],
    smtp_settings[:port],
    smtp_settings[:domain],
    smtp_settings[:user_name],
    smtp_settings[:password],
    smtp_settings[:authentication]
) do |smtp|
    smtp.enable_starttls
    smtp.send_message message, '[email protected]', '[email protected]'
end
Replace [email protected], YOUR_SMTP_USERNAME and YOUR_SMTP_PASSWORD with an email address from your domain (that is added to your AhaSend account), and your actual SMTP credential username and password.

Sending with the Mail gem

The Mail gem is a library that uses net/smtp and other networking libraries from the standard library internally for all its networking actions, and provides a high-level interface for parsing, generating and sending email messages using Ruby.

require 'mail'

Mail.defaults do
    delivery_method :smtp, {
    address: 'send.ahasend.com',
    port: 587,
    user_name: 'YOUR_SMTP_USERNAME',
    password: 'YOUR_SMTP_PASSWORD',
    authentication: 'plain',
    enable_starttls_auto: true
    }
end

mail = Mail.new do
    from     '[email protected]'
    to       '[email protected]'
    subject  'Here is the HTML message with an attachment'
    html_part do
    content_type 'text/html; charset=UTF-8'
    body '<h1>This is HTML content</h1><p>This is a paragraph in HTML.</p>'
    end
    add_file '/path/to/attachment.jpg'
end

mail.deliver!
Don't forget to replace [email protected], YOUR_SMTP_USERNAME, YOUR_SMTP_PASSWORD and /path/to/attachment.jpg with the appropriate values.

Sending emails with ActionMailer

ActionMailer is part of the Ruby on Rails framework and provides a simple yet customizable way for working with and sending emails. If you're using Ruby on Rails to develop your application, ActionMailer is your best choice for sending emails.

To get started, configure your SMTP settings in config/environments/production.rb (or development.rb for testing):

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
    address: 'send.ahasend.com',
    port: 587,
    domain: 'example.com', # your domain
    user_name: 'YOUR_SMTP_USERNAME',
    password: 'YOUR_SMTP_PASSWORD',
    authentication: 'plain',
    enable_starttls_auto: true
}

Create an HTML view for the email in app/views/user_mailer/welcome_email.html.erb:

<!DOCTYPE html>
<html>
    <head>
        <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
    </head>
    <body>
        <h1>Welcome to My Awesome Site</h1>
        <p>
        You have successfully signed up to example.com,
        your username is: <%= @user.username %>.<br>
        </p>
    </body>
</html>

Now create a mailer class with an HTML view and optionally specify the attachments:

# app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
    default from: '[email protected]'

    def welcome_email(user)
        attachments['filename.jpg'] = File.read('/path/to/attachment.jpg')
        mail(to: user.email, subject: 'Welcome to My Awesome Site') do |format|
            format.html { render 'another_template' }
        end
    end
end
Again, Don't forget to replace [email protected], YOUR_SMTP_USERNAME, YOUR_SMTP_PASSWORD and /path/to/attachment.jpg with the appropriate values.

These libraries and gems are quite powerful and flexible, supporting a wide range of features from simple plaintext emails to complex messages with HTML content and attachments. This guide covered the basics to get you started. For more advanced features and options, please refer to the official documentation:

AhaSend
Send up to 1,000 emails per month on us, no credit card required!