Rails: change default sender in action mailer

2019-04-30 06:03发布

问题:

I am sending email using action mailer in my rails app. But it allows only one default sender. This is my UserMailer class:

class UserMailer < ActionMailer::Base
 default :from => "example@example.com"
 def welcome_email(user, order)
  @user = user
  @order = order
  mail(:to => user.email, :subject => "Your Order")
 end
 def signup_email(user)
  @user = user
  mail(:to => user.email, :subject => "Thank you.")
 end
 def invite_confirm(curuser,usemail,post)
  @greeting = "Hi"
  @user = curuser
  @post = post
  mail(:to => user.email, :subject => "Hello")
 end
end

I tried this:

class UserMailer < ActionMailer::Base
 def welcome_email(user, order)
@user = user
    @order = order
    mail(:to => user.email, :subject => "Your Order", :from => "abc@xyz.com")
 end
 def signup_email(user)
   @user = user
   mail(:to => user.email, :subject => "Thank you.", :from => "qwe@asd.com")
 end
 def invite_confirm(curuser,usemail,post)
  @greeting = "Hi"
  @user = curuser
  @post = post
  mail(:to => user.email, :subject => "Hello", :from => "zyx@asd.com")
 end
end

But still it is sending email from "example@example.com"

Is there any way to change sender for each method written in UserMailer class? Am i supposed to change anywhere else?

In config/environments/development.rb and config/environments/production.rb i have this:

 config.action_mailer.smtp_settings = {
  :address => "smtp.gmail.com",
  :port => "587",
  :domain => "gmail.com",
  :authentication => "plain",
  :user_name => "example@example.com",
  :password => "example",
  :enable_starttls_auto => true 
 }

I guess, i should not change anything here.

回答1:

You can pass it as a parameter to the mail method:

def new_mail
  mail from: "example@example.com", to: "user@example.com"
end


回答2:

I think you want to send mail with three different emails of the for-each action. Because you use gmail, you need Sending mail from a different address.

No single vendor is optimal for all three types of email; you likely will use several vendors.

For “company email,” that is, sending individual email to customers or business associates, you’ll probably use Gmail or Google Apps for Business. For a single address, you can set up a single Gmail account to receive and send email from a different address. More likely, you’ll want several email addresses for your company mail. For that, use Google Apps for Business.

Send Email with Rails



回答3:

I found that, this can't be done using smtp. Need to use amazon SES which allows multi sender support.



回答4:

Here's what i use, it allows to make a "title" different.

class UserMailer < ActionMailer::Base
      default :from => '"example" <example@domain.com>'

      def send_signup_email(user)
        @user = user
        mail(to: @user.email, subject: 'example')
      end
    end