如何使用Ruby的邮件gem通过smtp发送电子邮件?

Col*_*nic 41 ruby email smtp

我正在使用mailgem for Ruby https://github.com/mikel/mail

如何通过smtp服务器发送电子邮件?如何指定地址和端口?我应该为Gmail使用哪些设置?

READMEGitHub上只给出实例由本地服务器发送.

Sim*_*tti 96

来自http://lindsaar.net/2010/3/15/how_to_use_mail_and_actionmailer_3_with_gmail_smtp

要通过GMail发送,您需要将Mail::SMTP类配置为具有正确的值,因此要尝试此操作,请打开IRB并键入以下内容:

require 'mail'

options = { :address              => "smtp.gmail.com",
            :port                 => 587,
            :domain               => 'your.host.name',
            :user_name            => '<username>',
            :password             => '<password>',
            :authentication       => 'plain',
            :enable_starttls_auto => true  }



Mail.defaults do
  delivery_method :smtp, options
end
Run Code Online (Sandbox Code Playgroud)

最后一个块调用Mail.defaults允许我们为从现在开始创建的所有邮件对象设置全局传递方法.高级用户提示,您不必使用全局方法,您可以直接在任何单个Mail::Message对象上定义delivery_method,并且每封电子邮件都有不同的传递代理,如果您构建的应用程序具有多个具有不同服务器处理的用户,这将非常有用电子邮件.

Mail.deliver do
       to 'mikel@test.lindsaar.net'
     from 'ada@test.lindsaar.net'
  subject 'testing sendmail'
     body 'testing sendmail'
end
Run Code Online (Sandbox Code Playgroud)

  • 我收到以下错误:`/usr/local/rvm/rubies/ruby-1.9.3-p327/lib/ruby/1.9.1/net/smtp.rb:960:in'check_auth_response':534-5.7 .14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvUX(Net :: SMTPAuthenticationError)` - 我对连接数据进行了三次检查,确定无误. (3认同)
  • @kitsched检查您的Gmail帐户中的安全设置.Gmail阻止了可疑活动.您需要转到设置并确认,您知道该活动 (3认同)