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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12884711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:27:27  来源:igfitidea点击:

How to send email via smtp with Ruby's mail gem?

rubyemailsmtp

提问by Colonel Panic

I am using the mailgem for Ruby https://github.com/mikel/mail

我正在将mailgem 用于 Ruby https://github.com/mikel/mail

How do I send an email via an smtp server? How do I specify the address and port? And what settings should I use for Gmail?

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

The READMEon github only gives examples sending by a local server.

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

回答by Simone Carletti

From http://lindsaar.net/2010/3/15/how_to_use_mail_and_actionmailer_3_with_gmail_smtp

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

To send out via GMail, you need to configure the Mail::SMTPclass to have the correct values, so to try this out, open up IRB and type the following:

要通过 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

The last block calls Mail.defaultswhich allows us to set the global delivery method for all mail objects that get created from now on. Power user tip, you don't have to use the global method, you can define the delivery_method directly on any individual Mail::Messageobject and have different delivery agents per email, this is useful if you are building an application that has multiple users with different servers handling their email.

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

Mail.deliver do
? ? ? ?to '[email protected]'
? ? ?from '[email protected]'
? subject 'testing sendmail'
? ? ?body 'testing sendmail'
end