在Ruby on Rails環境下要發送email,以下是步驟:
一.修改設定檔
修改config/application.rb,加入以下
config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'smtp.gmail.com' , port: 587 , domain: 'gmail.com' , user_name: 'your mail address' , password: 'your mail password' , authentication: 'plain' , enable_starttls_auto: true } |
二.在app/mailers/下增加user_mailer.rb
class UserMailer < ActionMailer::Base default from: 'notifications@example.com' def welcome_email(user) @user = user mail(to: @user .email, subject: 'Welcome to My Awesome Site' ) end end |
三.增加你的mail template
在app/views/user_mailer目錄下新增sendMail.text.rb
Welcome to example.com, <%= @user .name %> =============================================== You have successfully signed up to example.com, your username is: <%= @user .login %> . To login to the site, just follow this link: <%= @url %> . Thanks for joining and have a great day! |
四.測試看看
之後你就可以在任一controller/action下發送email,呼叫Action Mailer
def sendMail
@user = User.find(user_id)
UserMailer.sendMail(@user).deliver
end
完成以上步驟應該可以成功寄出email了
參考文章:
Action Mailer Basics