---
title: "send mail in rails"
author: "clark1231"
date: "2012-10-22T14:48:48Z"
tags: ["Rails"]
categories: ["互联网"]
slug: "send-mail-in-rails"
draft: false
lastmod: "2012-10-22T14:51:11Z"
id: 1703008
url: "https://caok1231.iteye.com/blog/1703008"
---

**Creating and Sending Mail**

**1.CREATE A Notice MAILER**

```
rails g mailer NoticeMailer decomp_change
```

**create   app/mailers/notice\_mailer.rb**

**invoke   erb**

**create   app/views/notice\_mailer**

**create   app/views/notice\_mailer/decomp\_change.text.erb**

**app/mailers/notice\_mailer.rb**

```
class NoticeMailer < ActionMailer::Base
  default from: "from@example.com"

  def decomp_change
    @greeting = "Hi"
    mail to: "to@example.org"
  end
end
```

 

**Sending Attachments in Mail**

```
class NoticeMailer < ActionMailer::Base
  default from: "from@example.com"

  def decomp_change (notice)
    @notice = notice
    @last_tweet = @notice.tweets.last
    attachments['z.pdf'] = File.read("#{Rails.root}/public/notice.pdf")
    mail to: @notice.email, subject: 'Your decomp stage has changed'
  end
end
```

 

**2.MAILER VIEWS**

**app/views/notice\_mailer/decomp\_change.text.erb**

```
Greetings <%= @notice.name %>,

  Your decomposition state is now <%= @notice.decomp %> and your
last tweet was: <%= @last_tweet.body %>

Good luck!
```

 

**app/views/notice\_mailer/decomp\_change.html.erb**

```
<h1>Greetings <%= @notice.name %>,</h1>

<p>Your decomposition state is now <%= @notice.decomp %> and your
last tweet was: <%= @last_tweet.body %></p>

<%= link_to "View yourself", notice_url(@notice) %>
```

**3.SENDING MAIL**

**app/models/notice.rb**

```
class Notice < ActiveRecord::Base
  after_save :decomp_change_notification, if: :decomp_changed?

  private
  def decomp_change_notification
    noticeMailer.decomp_change(self).deliver
  end
end
```

 

**4.config**

**config/environments/development.rb**

```
config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address              => "smtp.gmail.com",
    :port                 => 587,
    :user_name            => 'poshboytl',
    :password             =>  ENV['GMAIL_PASS'],
    :authentication       => 'plain',
    :enable_starttls_auto => true
  }
```

 

reference:

**http://railscasts-china.com/episodes/how-to-send-emails-in-rails**