Sign In

How to send multipart (HTML and plain text) emails with attachments using Rails:

  1. Generate a mailer:
rails generate mailer UserMailer
  1. In your mailer class (e.g. app/mailers/user_mailer.rb), define a method for your email:
class UserMailer < ApplicationMailer
  def welcome_email(user)
    @user = user
    attachments['filename.jpg'] = File.read('/path/to/filename.jpg')

    mail(to: @user.email, subject: 'Welcome to Our Site') do |format|
      format.html
      format.text
    end
  end
end
  1. Create two view templates for your email:
  • app/views/user_mailer/welcome_email.html.erb (HTML version)
  • app/views/user_mailer/welcome_email.text.erb (Plain text version)
  1. In your HTML template (welcome_email.html.erb):
<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Welcome to our site, <%= @user.name %></h1>
    <p>
      You have successfully signed up to our site.<br>
    </p>
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>
  1. In your plain text template (welcome_email.text.erb):
Welcome to our site, <%= @user.name %>

You have successfully signed up to our site.

Thanks for joining and have a great day!
  1. To send the email, call the mailer method from your controller:
UserMailer.welcome_email(@user).deliver_now
  1. Configure your email settings in config/environments/development.rb (and production.rb for production):
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address:              'smtp.gmail.com',
  port:                 587,
  domain:               'example.com',
  user_name:            '<username>',
  password:             '<password>',
  authentication:       'plain',
  enable_starttls_auto: true
}

This setup will:

  • Send both HTML and plain text versions of the email
  • Include the attachment
  • Allow the email client to choose which version to display based on its capabilities

Remember to replace the SMTP settings with your actual email provider’s details. For production, it’s recommended to use environment variables for sensitive information like passwords.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *