2014-01-20 21 views
4

我正在使用Ruby on Rails,您能教我如何使用Mandrill發送和接收郵件。如何使用Mandrill發送和獲取郵件?

我的問題是當用戶輸入文本並按提交,我想要發送郵件到我的郵件。 我已閱讀文檔,但我不明白。

這是我development.rb,同production.rb

ActionMailer::Base.smtp_settings = { 
    :port =>   '587', 
    :address =>  'smtp.mandrillapp.com', 
    :user_name =>  '[email protected]', 
    :password =>  's82SlRM5dPiKL8vjrJfj4w', 
    :domain =>   'heroku.com', 
    :authentication => :plain 
} 
ActionMailer::Base.delivery_method = :smtp 

user_mailer.rb:

class UserMailer < ActionMailer::Base 
    default from: "[email protected]" 
    def welcome 
    mail(to: "[email protected]", subject: "Welcome", body: "Have a nice day") 
    end 
end 

和控制器:

def index 
    UserMailer.welcome.deliver 
end 

我的日誌文件看起來像這個:

Started GET "https://stackoverflow.com/users/" for 127.0.0.1 at 2014-01-21 16:14:10 +0700 
Processing by UsersController#index as HTML 

Sent mail to [email protected] (2008.0ms) 
Date: Tue, 21 Jan 2014 16:14:10 +0700 

From: [email protected] 

To: [email protected] 

Message-ID: <[email protected]> 

Subject: Welcome 

Mime-Version: 1.0 

Content-Type: text/plain; 

charset=UTF-8 

Content-Transfer-Encoding: 7bit 



Have a nice day 
    Rendered text template (0.0ms) 
Completed 200 OK in 2018ms (Views: 1.0ms | ActiveRecord: 0.0ms) 

回答

5

首先,您需要在mandrill.com上創建帳戶。

登錄後,選擇集成類型:SMTP或API。在大多數情況下,SMTP將適用於您。

點擊SMTP,創建你的API密鑰。

然後在你的development.rb或production.rb文件 添加這些行:

config.action_mailer.smtp_settings = { 
    :port =>   '587', 
    :address =>  'smtp.mandrillapp.com', 
    :user_name =>  ENV['MANDRILL_USERNAME'], 
    :password =>  ENV['MANDRILL_APIKEY'], 
    :domain =>   'domain.com', 
    :authentication => :plain 
} 

這基本上就是全部。現在你可以發送電子郵件與Mandrill。

編輯

也可以嘗試添加到您在您的環境文件,這些生產線來進行交付和提高,如果任何傳送錯誤。還添加default_url_options - 在發展本地主機:試驗前的3000,在生產heroku.com

config.action_mailer.perform_deliveries = true 
config.action_mailer.raise_delivery_errors = true 
config.action_mailer.default_url_options = { host: "localhost:3000" } 

重新啓動您的應用程序

EDIT 2

如果你想的ActionMailer對提交按鈕發送電子郵件單擊,然後您需要移動UserMailer.welcome.deliver以創建相應控制器的動作。

def create 
    if @object.save 
    UserMailer.welcome.deliver 
    else 
    render "new" 
    end 
end 
+0

謝謝,我試過了,但我還沒有收到任何郵件。 'default from:「[email protected]」 def welcome_email 郵件(至:[email protected],主題:「Welcome to my website」) end' – user3214298

+0

您是否使用過正確的用戶名和apikey?暫時刪除'ENV []',然後插入純字符串。還要確保在你的環境.rb文件中有'config.action_mailer.delivery_method =:smtp'。 –

+0

感謝您的幫助,但它仍然無法正常工作...我發佈了我的文件內容... – user3214298

相關問題