Search code examples
ruby-on-railsrubyemailsmtpmail-gem

How to specify who is sending the email with the `mail` gem?


I am sending emails with the mail gem, using the very simple code below. When I'm sending an email, the smtp_account.user_name and the smtp_account.from could be e.g. support@thebestcompany.com. This causes the recipient to see that he has received an email from support (you know, in his inbox where he can get an overview of his last x emails). How can I specify this, so the recipient gets to see something more interesting, like e.g. The Best Company?

require 'mail'

class SmtpMails

  def self.send_mails(smtp_account, to, subject, text)
    options = {
      :address              => smtp_account.address,
      :port                 => smtp_account.port,
      :domain               => smtp_account.domain,
      :user_name            => smtp_account.user_name,
      :password             => smtp_account.password,
      :authentication       => smtp_account.authentication,
      :enable_starttls_auto => smtp_account.enable_starttls_auto
    }

    Mail.defaults do
      elivery_method :smtp, options
    end

    mail = Mail.deliver do
      to to
      from smtp_account.from
      subject subject
    end
  end
end

Solution

  • You'll need to add some additional information when specifying the sender of the email. The following code snippet should do what you want:

    mail = Mail.deliver do
      to to
      from "The Best Company <#{smtp_account.from}>"
      subject subject
    end
    

    Putting the email address between the < and > brackets is the standard practice for adding a friendly name for the email being sent.