如何使用Mandrill发送和接收邮件?

4

我正在使用Ruby on Rails,你能教我如何使用Mandrill发送和接收邮件吗。

我的问题是当用户输入文本并提交时,我希望消息发送到我的邮箱。 我已经阅读了文档,但我不理解它。

这是我的development.rb文件,与production.rb相同。

ActionMailer::Base.smtp_settings = {
    :port =>           '587',
    :address =>        'smtp.mandrillapp.com',
    :user_name =>      'myemail@gmail.com',
    :password =>       's82SlRM5dPiKL8vjrJfj4w',
    :domain =>         'heroku.com',
    :authentication => :plain
}
ActionMailer::Base.delivery_method = :smtp

user_mailer.rb:

class UserMailer < ActionMailer::Base
  default from: "from@example.com"
  def welcome
    mail(to: "morumotto26@gmail.com", subject: "Welcome", body: "Have a nice day")
  end 
end

在控制器中:

def index
  UserMailer.welcome.deliver
end

我的日志文件看起来像这样:

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

Sent mail to morumotto26@gmail.com (2008.0ms)
Date: Tue, 21 Jan 2014 16:14:10 +0700

From: myemail@gmail.com

To: morumotto26@gmail.com

Message-ID: <52de3a62c89b2_5e8c9ea1881631@tnkjapan10.mail>

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)
1个回答

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发送电子邮件了。

编辑

同时尝试向你的环境文件中添加以下行来执行传递并在需要时引发传递错误。还要添加默认的url_options - 在开发中是localhost: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" }

在测试之前,请重新启动您的应用程序。

编辑2

如果您希望ActionMailer在提交按钮单击时发送电子邮件,则需要将UserMailer.welcome.deliver移动到相应控制器的create操作中。

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

谢谢,我尝试了,但我还没有收到任何邮件。 默认发件人:"myemail@gmail.com" def welcome_email mail(to: blahblah@gmail.com, subject: "欢迎来到我的网站") end - user3214298
你是否使用了正确的用户名和 API 密钥?暂时删除 ENV[] 并插入纯字符串。另外,请确保在你的环境 .rb 文件中有 config.action_mailer.delivery_method =:smtp - Ilya Cherevkov
当您打开索引操作时,您的日志文件是什么样子? - Ilya Cherevkov
ActionMailer::Base 重命名为 config.action_mailer,就像我的答案中所示。此外,您可以尝试直接将 ActionMailer::Base.smtp_settings = {}ActionMailer::Base.delivery_method 移动到您的 user_mailer.rb 中。 - Ilya Cherevkov
谢谢,但是它没有运行,兄弟。我不知道为什么 :( - user3214298
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接