这里是 Net::SMTP#start 调用的描述:
http://ruby-doc.org/stdlib-1.9.1/libdoc/net/smtp/rdoc/Net/SMTP.html#method-i-start
该页面提到您只需执行 SMTP.start 即可一次完成所有操作。
看起来您缺少端口参数。尝试使用端口 587 进行安全身份验证,如果这不起作用,请使用端口 25。(查看下面提到的教程)
您的电话应如下所示:
message_body = <<END_OF_EMAIL
From: Your Name <your.name@gmail.com>
To: Other Email <other.email@somewhere.com>
Subject: text message
This is a test message.
END_OF_EMAIL
server = 'smtp.gmail.com'
mail_from_domain = 'gmail.com'
port = 587 # or 25 - double check with your provider
username = 'your.name@gmail.com'
password = 'your_password'
smtp = Net::SMTP.new(server, port)
smtp.enable_starttls_auto
smtp.start(server,username,password, :plain)
smtp.send_message(message_body, fromAddress, toAddress) # see note below!
重要:
-
请注意,您需要在 message_body 中添加 To: 、 From: 、 Subject: 标头!
- 您的 SMTP 服务器将添加 Message-Id: 和 Date: 标头
还要检查:
从 Ruby 发送电子邮件的另一种方式:
您可以使用 Rails 中的 ActionMailer gem 从 Ruby 发送电子邮件(不使用 Rails)。
起初这似乎有点矫枉过正,但这样会更容易,因为您不必使用 To: 、 From: 、 Subject: 、 Date: 、 Message-Id: Headers 来格式化邮件正文.
# usage:
# include Email
#
# TEXT EMAIL :
# send_text_email( 'sender@somewhere.com', 'sender@somewhere.com,receiver@other.com', 'test subject', 'some body text' )
# HTML EMAIL :
# send_html_email( 'sender@somewhere.com', 'sender@somewhere.com,receiver@other.com', 'test subject', '<html><body><h1>some title</h1>some body text</body></html>' )
require 'action_mailer'
# ActionMailer::Base.sendmail_settings = {
# :address => "Localhost",
# :port => 25,
# :domain => "yourdomain.com"
# }
ActionMailer::Base.smtp_settings = { # if you're using GMail
:address => 'smtp.gmail.com',
:port => 587,
:domain => 'gmail.com',
:user_name => "your-username@gmail.com"
:password => "your-password"
:authentication => "plain",
:enable_starttls_auto => true
}
class SimpleMailer < ActionMailer::Base
def simple_email(the_sender, the_recepients, the_subject, the_body , contenttype = nil)
from the_sender
recipients the_recepients
subject the_subject
content_type contenttype == 'html' ? 'text/html' : 'text/plain'
body the_body
end
end
# see http://guides.rails.info/action_mailer_basics.html
# for explanation of dynamic ActionMailer deliver_* methods.. paragraph 2.2
module Email
# call this with a message body formatted as plain text
#
def send_text_email( sender, recepients, subject, body)
SimpleMailer.deliver_simple_email( sender , recepients , subject , body)
end
# call this with an HTML formatted message body
#
def send_html_email( sender, recepients, subject, body)
SimpleMailer.deliver_simple_email( sender , recepients , subject , body, 'html')
end
endsubject , body, 'html')
end
end
例如如果您想使用 Gmail 的 SMTP 服务器通过您的 Gmail 帐户发送电子邮件,则上面的代码可以工作。其他 SMTP 服务器可能需要 :port、:authentication 和 :enable_starttls_auto 的其他值,具体取决于 SMTP 服务器设置