从rails console发送电子邮件

Max*_*ams 56 sendmail ruby-on-rails

我正试图从我的生产服务器上的控制台发送一些邮件,但他们没有出去.我无法理解为什么.我只使用sendmail标准的电子邮件设置.当我调用Mailer.deliver_方法时,我得到了回复:

#<TMail::Mail port=#<TMail::StringPort:id=0x3fe1c205dbcc> bodyport=#<TMail::StringPort:id=0x3fe1c2059e00>>
Run Code Online (Sandbox Code Playgroud)

编辑:添加了一些更多信息:

因此,例如,当新用户注册时,我在我的控制器中有这一行,向他们发送"欢迎"电子邮件:

 Mailer.deliver_signup(@user, request.host_with_port, params[:user][:password])
Run Code Online (Sandbox Code Playgroud)

这很好用.我认为我应该可以从控制台做同样的事情,例如

user = User.find(1)
Mailer.deliver_signup(user, "mydomainname.com", "password")
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我得到了Tmail :: StringPort对象,但邮件似乎没有被发送出去(我正在尝试向自己发送电子邮件来测试这个).

我在ubuntu服务器上以防万一.谢谢 - 最大

jmg*_*ier 96

更快版本:

ActionMailer::Base.mail(
  from: "test@example.co", 
  to: "valid.recipient@domain.com", 
  subject: "Test", 
  body: "Test"
).deliver_now
Run Code Online (Sandbox Code Playgroud)

  • 这是更好的,虽然`deliver`已被弃用,但鼓励使用`deliver_now`. (5认同)
  • 我将如何使用现有的模板?就像 UserMailer.account_activation 电子邮件.. (2认同)

ssc*_*rus 47

今天早上我在一个Rails 3应用程序上遇到了类似的问题,我打电话给:

UserMailer.activation_instructions(@user)
Run Code Online (Sandbox Code Playgroud)

这给了我数据,但没有发送电子邮件.要发送,我打电话给:

UserMailer.activation_instructions(@user).deliver
Run Code Online (Sandbox Code Playgroud)

这样做了.希望这对你也有用!

  • 似乎不适合我,你必须明确设置rails env所以它选择正确的actiomailer环境配置? (3认同)

Dhi*_*raj 28

要首先从Rails控制台发送电子邮件,我们必须在控制台中执行此设置以执行操作邮件设置.

ActionMailer::Base.delivery_method = :smtp 
ActionMailer::Base.smtp_settings = {
  address: 'smtp.gmail.com', 
  port: 587, 
  domain: 'gmail.com',
  authentication: 'plain', 
  enable_starttls_auto: true, 
  user_name: 'your@gmail.com',
  password: 'yourpassword'
}
Run Code Online (Sandbox Code Playgroud)

之后如果我们执行电子邮件发送代码,它将发送电子邮件.

UserMailer.activation_instructions(@user).deliver_now
Run Code Online (Sandbox Code Playgroud)


小智 5

如果你想发送附件

mailer = ActionMailer::Base.new
mailer.attachments["file.jpg"] = File.read("/dir/file.jpg")
mailer.attachments["file.txt"] = "some text"
mailer.mail(from: "me@example.com",
            to: "you@example.com",
            subject: "Email with attachments",
            body: "included the documents below\n\n")
mailer.message.deliver
Run Code Online (Sandbox Code Playgroud)

mail必须位于附件之后,因为它创建标题。