Mailers
-
应将 mailer 命名为
SomethingMailer。若没有 Mailer 后缀,不能立即断定它是否为一个 mailer,也不能断定哪个视图与它有关。 -
提供 HTML 与纯文本两份视图模版。
-
在开发环境下应显示发信失败错误。这些错误默认是关闭的。
## config/environments/development.rb
config.action_mailer.raise_delivery_errors = true
- 在开发环境下使用诸如 Mailcatcher 的本地 SMTP 服务器。
## config/environments/development.rb
config.action_mailer.smtp_settings = {
address: 'localhost',
port: 1025,
# 更多设置
}
- 为域名设置默认项。
## config/environments/development.rb
config.action_mailer.default_url_options = { host: "#{local_ip}:3000" }
## config/environments/production.rb
config.action_mailer.default_url_options = { host: 'your_site.com' }
## 在 mailer 类中
default_url_options[:host] = 'your_site.com'
- 若需要在邮件中添加到网站的超链接,应总是使用
_url方法,而非
_path方法。_url方法产生的超链接包含域名,而_path
方法产生相对链接。
## 差
You can always find more info about this course
<%= link_to 'here', course_path(@course) %>
## 好
You can always find more info about this course
<%= link_to 'here', course_url(@course) %>
- 正确地设置寄件人与收件人地址的格式。应使用下列格式:
## 在你的 mailer 类中
default from: 'Your Name <info@your_site.com>'
- 确保测试环境下的 email 发送方法设置为
test:
## config/environments/test.rb
config.action_mailer.delivery_method = :test
- 开发环境和生产环境下的发送方法应设置为
smtp:
## config/environments/development.rb, config/environments/production.rb
config.action_mailer.delivery_method = :smtp
-
当发送 HTML 邮件时,所有样式应为行内样式,这是因为某些客户端不能正确显示外部样式。然而,这使得邮件难以维护理并会导致代码重复。有两个类似的 gem 可以转换样式,并将样式放在对应的 html 标签里: premailer-rails3 和 roadie。
-
避免在产生页面响应的同时发送邮件。若有多个邮件需要发送,这会导致页面加载延迟甚至请求超时。有鉴于此,应使用 sidekiq 这个 gem 在后台发送邮件。
