## Mailers
* <a name="mailer-name"></a>
應將 mailer 命名為 `SomethingMailer`。若沒有 Mailer 后綴,不能立即斷定它是否為一個 mailer,也不能斷定哪個視圖與它有關。
<sup>[[link](#mailer-name)]</sup>
* <a name="html-plain-email"></a>
提供 HTML 與純文本兩份視圖模版。
<sup>[[link](#html-plain-email)]</sup>
* <a name="enable-delivery-errors"></a>
在開發環境下應顯示發信失敗錯誤。這些錯誤默認是關閉的。
<sup>[[link](#enable-delivery-errors)]</sup>
```Ruby
# config/environments/development.rb
config.action_mailer.raise_delivery_errors = true
```
* <a name="local-smtp"></a>
在開發環境下使用諸如 [Mailcatcher](https://github.com/sj26/mailcatcher) 的本地 SMTP 服務器。
<sup>[[link](#local-smtp)]</sup>
```Ruby
# config/environments/development.rb
config.action_mailer.smtp_settings = {
address: 'localhost',
port: 1025,
# 更多設置
}
```
* <a name="default-hostname"></a>
為域名設置默認項。
<sup>[[link](#default-hostname)]</sup>
```Ruby
# 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'
```
* <a name="url-not-path-in-email"></a>
若需要在郵件中添加到網站的超鏈接,應總是使用 `_url` 方法,而非
`_path` 方法。`_url` 方法產生的超鏈接包含域名,而 `_path`
方法產生相對鏈接。
<sup>[[link](#url-not-path-in-email)]</sup>
```Ruby
# 差
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) %>
```
* <a name="email-addresses"></a>
正確地設置寄件人與收件人地址的格式。應使用下列格式:
<sup>[[link](#email-addresses)]</sup>
```Ruby
# 在你的 mailer 類中
default from: 'Your Name <info@your_site.com>'
```
* <a name="delivery-method-test"></a>
確保測試環境下的 email 發送方法設置為 `test`:
<sup>[[link](#delivery-method-test)]</sup>
```Ruby
# config/environments/test.rb
config.action_mailer.delivery_method = :test
```
* <a name="delivery-method-smtp"></a>
開發環境和生產環境下的發送方法應設置為 `smtp`:
<sup>[[link](#delivery-method-smtp)]</sup>
```Ruby
# config/environments/development.rb, config/environments/production.rb
config.action_mailer.delivery_method = :smtp
```
* <a name="inline-email-styles"></a>
當發送 HTML 郵件時,所有樣式應為行內樣式,這是因為某些客戶端不能正確顯示外部樣式。然而,這使得郵件難以維護理并會導致代碼重復。有兩個類似的 gem 可以轉換樣式,并將樣式放在對應的 html 標簽里: [premailer-rails3](https://github.com/fphilipe/premailer-rails3) 和
[roadie](https://github.com/Mange/roadie)。
<sup>[[link](#inline-email-styles)]</sup>
* <a name="background-email"></a>
避免在產生頁面響應的同時發送郵件。若有多個郵件需要發送,這會導致頁面加載延遲甚至請求超時。有鑒于此,應使用 [sidekiq](https://github.com/mperham/sidekiq) 這個 gem 在后臺發送郵件。
<sup>[[link](#background-email)]</sup>