Sending Emails with SMTP in Ruby

Send emails through AhaSend’s SMTP servers using Ruby’s versatile email solutions. This guide covers three popular approaches: the built-in net/smtp library, the powerful Mail gem, and Rails’ ActionMailer framework.
Ruby’s Email Flexibility: Ruby offers multiple excellent options for email sending, from lightweight standard library solutions to feature-rich frameworks - choose the one that best fits your application’s needs.

Prerequisites

Before you begin, ensure you have:
Need SMTP Credentials? If you haven’t created SMTP credentials yet, check out our SMTP Credentials guide for step-by-step instructions.

Ruby Email Solutions Overview

Ruby provides multiple excellent options for sending emails via SMTP:

Standard Library

Best for: Simple, lightweight email sending
Pros: No dependencies
Cons: Verbosity
Use case: Scripts

Mail Gem

Best for: non-Rails applications
Pros: High-level API
Cons: Ext. dependency
Use case: Standalone apps

ActionMailer (Rails)

Best for: Rails applications
Pros: Rails integration, templates, testing
Cons: Rails-specific
Use case: Web applications, MVC pattern

Connection Settings

Use these settings for all Ruby SMTP configurations with AhaSend:

Primary Server

Host: send.ahasend.com
Ports: 587 (recommended), 25, 2525
Security: STARTTLS
Authentication: Required

US Server

Host: send-us.ahasend.com
Ports: 587 (recommended), 25, 2525
Security: STARTTLS
Authentication: Required

Method 1: Using net/smtp (Standard Library)

The net/smtp library is part of Ruby’s standard library, offering a lightweight solution for sending emails without external dependencies.
Standard Library Advantage: net/smtp comes with Ruby - no gem installation required! Perfect for simple scripts and lightweight applications.

Basic Examples

require 'net/smtp'

def send_plain_text_email
  # SMTP server configuration
  smtp_settings = {
    address: 'send.ahasend.com',
    port: 587,
    domain: 'yourdomain.com',
    user_name: 'YOUR_SMTP_USERNAME',
    password: 'YOUR_SMTP_PASSWORD',
    authentication: 'plain',
    enable_starttls_auto: true
  }

  # Email content
  from_email = '[email protected]'
  to_email = '[email protected]'
  subject = 'Welcome to our platform!'
  body = 'Thanks for signing up. We\'re excited to have you!'

  # Construct the email message
  message = <<~MESSAGE_END
    From: Your Company <#{from_email}>
    To: #{to_email}
    Subject: #{subject}
    Date: #{Time.now.rfc2822}
    Content-Type: text/plain; charset=UTF-8

    #{body}
  MESSAGE_END

  # Send the email
  begin
    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, from_email, to_email)
    end

    puts "Email sent successfully!"
  rescue => e
    puts "Failed to send email: #{e.message}"
  end
end

# Send the email
send_plain_text_email

Method 2: Using the Mail Gem

The Mail gem provides a high-level, Ruby-style interface for email handling with rich features like attachments, multipart messages, and template support.
Mail Gem Benefits: Clean API, automatic MIME handling, built-in attachment support, and excellent template integration. Perfect for complex email applications.

Installation

Add the Mail gem to your project:
# Add to your Gemfile
gem 'mail'

# Then run:
bundle install

Basic Examples

require 'mail'

# Configure Mail gem defaults
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

def send_plain_text_email
  begin
    mail = Mail.new do
      from     '[email protected]'
      to       '[email protected]'
      subject  'Welcome to our platform!'
      body     'Thanks for signing up. We\'re excited to have you!'
    end

    mail.deliver!
    puts "Email sent successfully!"
  rescue => e
    puts "Failed to send email: #{e.message}"
  end
end

send_plain_text_email

Advanced Mail Gem Features

require 'mail'

# Configure Mail gem defaults
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

def send_email_with_special_headers
  begin
    mail = Mail.new do
      from     '[email protected]'
      to       ['[email protected]', '[email protected]']
      cc       '[email protected]'
      bcc      '[email protected]'
      subject  'Product Updates with Tracking'

      # Add AhaSend special headers
      header['ahasend-track-opens'] = 'true'
      header['ahasend-track-clicks'] = 'true'
      header['ahasend-tags'] = 'product-update,newsletter,ruby'
      header['ahasend-message-retention'] = '30'
      header['ahasend-message-data-retention'] = '7'

      text_part do
        body 'Check out our latest features at https://yourdomain.com/features'
      end

      html_part do
        content_type 'text/html; charset=UTF-8'
        body <<~HTML
          <html>
          <body>
            <h1>Product Updates</h1>
            <p>Check out our <a href="https://yourdomain.com/features">latest features</a>!</p>
            <p>This email has tracking enabled and custom tags.</p>
          </body>
          </html>
        HTML
      end
    end

    mail.deliver!
    puts "Email sent with special headers!"
  rescue => e
    puts "Failed to send email: #{e.message}"
  end
end

send_email_with_special_headers

Method 3: Using ActionMailer (Rails)

ActionMailer is part of Ruby on Rails and provides a comprehensive email solution with MVC patterns, templates, and excellent testing support.
Rails Integration: ActionMailer seamlessly integrates with Rails applications, providing view templates, internationalization, background job support, and comprehensive testing utilities.

Configuration

Configure your SMTP settings in the appropriate environment file:
# Production environment configuration
Rails.application.configure do
  # Email configuration
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address: 'send.ahasend.com',
    port: 587,
    domain: 'yourdomain.com',
    user_name: ENV['SMTP_USERNAME'],
    password: ENV['SMTP_PASSWORD'],
    authentication: 'plain',
    enable_starttls_auto: true
  }

  # Set default host for URL generation
  config.action_mailer.default_url_options = {
    host: 'yourdomain.com',
    protocol: 'https'
  }
end

Basic Mailer Setup

class UserMailer < ActionMailer::Base
  default from: '[email protected]'

  def welcome_email(user)
    @user = user
    @url = root_url

    mail(
      to: user.email,
      subject: 'Welcome to our platform!'
    )
  end

  def notification_email(user, title, message)
    @user = user
    @title = title
    @message = message

    # Add AhaSend special headers
    headers['ahasend-track-opens'] = 'true'
    headers['ahasend-track-clicks'] = 'true'
    headers['ahasend-tags'] = 'notification,rails'

    mail(
      to: user.email,
      subject: title
    )
  end
end

Testing with Sandbox Mode

Use sandbox mode to safely test your Ruby email integration across all methods:
require 'net/smtp'

def send_sandbox_test
  smtp_settings = {
    address: 'send.ahasend.com',
    port: 587,
    domain: 'yourdomain.com',
    user_name: 'YOUR_SMTP_USERNAME',
    password: 'YOUR_SMTP_PASSWORD',
    authentication: 'plain'
  }

  message = <<~MESSAGE_END
    From: [email protected]
    To: [email protected]
    Subject: Sandbox Test Email
    AhaSend-Sandbox: true
    AhaSend-Sandbox-Result: deliver

    This email is sent in sandbox mode for testing.
  MESSAGE_END

  begin
    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

    puts "Sandbox email sent successfully!"
  rescue => e
    puts "Failed to send sandbox email: #{e.message}"
  end
end

send_sandbox_test
Sandbox Benefits: Emails sent in sandbox mode are free, trigger webhooks normally, and never actually deliver to recipients - perfect for development and testing.

Resources