注意点:sendgrid的password如果被在github中公开,则sendgrid账号会被禁止使用
开发环境中使用gmail
#与controller的使用规则类似,在终端运行下面的代码
rails g mailer UserMailer
#在user_mailer.rb文件中建立如下的代码:
class UserMailer < ApplicationMailer
default from: "[email protected]"
def welcome_email
mail(to: "[email protected]", subject: "Welcome to My Awesome Site")
end
end
#建立两个视图文件,分别是welcome_email.html.erb文件和welcome_email.text.erb文件:
#进行文件配置,在config/environments/developments.rb中添加如下代码:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = {host: "localhost:3000"}
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
user_name: "zhengjiajun121",
password: "xxx",
authentication: "plain",
enable_starttls_auto: true }
#在终端执行下面的文件,邮件可以从gmail邮箱发送至foxmail邮箱中:
UserMailer.welcome_email.deliver_now
开发环境中使用sendgrid
#类似controller操作 rails g mailer notification_user
class ApplicationMailer < ActionMailer::Base
default from: '[email protected]' #可以随意赋值
layout 'mailer'
end
class NotificationUserMailer < ApplicationMailer
def welcome
mail to: "[email protected]", subject: "welcome the app"
end
end
#config/environments/development.rb
config.action_mailer.default_url_options = { host: "localhost:3000" } #使得邮件中的链接地址有效
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
#config/initializers/sendgrid.rb
ActionMailer::Base.smtp_settings = {
:user_name => 'apikey',
#需要使用ENV['SENDGRID_API_KEY'],不然sendgrid的password被发布,账号会被禁止
:password => 'password',
:domain => 'zhengjiajun.com',
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}
#在终端执行
NotificationUserMailer.welcome.deliver_now
生产环境中使用sendgrid
#类似controller操作 rails g mailer notification_user
class ApplicationMailer < ActionMailer::Base
default from: '[email protected]' #可以随意赋值
layout 'mailer'
end
class NotificationUserMailer < ApplicationMailer
def welcome
mail to: "[email protected]", subject: "welcome the app"
end
end
#config/environments/development.rb
config.action_mailer.default_url_options = { host: "zhengjiajun.com } #使得邮件中的链接地址有效
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
#config/initializers/sendgrid.rb
ActionMailer::Base.smtp_settings = {
:user_name => 'apikey',
#需要使用ENV['SENDGRID_API_KEY'],不然sendgrid的password被发布,账号会被禁止
:password => 'password',
:domain => 'zhengjiajun.com',
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}
#在终端执行
NotificationUserMailer.welcome.deliver_now