我正在尝试使用mail gem发送电子邮件。但不幸的是,它不起作用。这是我的控制器。
def create
fn = params["firstname"]
ln = params["lastname"]
email = params["email"]
file = params["file"]
summery = params["summery"]
email_body = "Hello\n This is Your favorite website.\nA I want to personaly say hi."
mail = Mail.new do
from 'someone@gmail.com'
to email
subject "Saying Hi"
body email_body
end
mail.add_file(filename: file.original_filename, content: File.read(file.tempfile.path)) unless file.nil?
mail.deliver!
render json: {message: "A bug has been created", success: true}, status: 201
end
此代码正在产生此错误
Errno::ECONNREFUSED - 连接被拒绝 - “localhost”端口 25 的连接(2):
但是,当我安装mailcatcher并配置我的控制器以将邮件发送到 mailcatcher 时,我可以在我的 mailcatcher UI 中看到电子邮件。
Mail.defaults do
delivery_method :smtp, address: "localhost", port: 1025
end
我也将这两行添加到我的 config/environment/development.rb
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
从我的搜索中,我看到有些人提到不要在开发模式下发送电子邮件,但是在这种情况下,我真的想测试全部功能。
更新
正如@Uzbekjon 和@SimoneCarletti 建议的那样,我将代码更改为使用ActionMailer。我在 app/mailer/ 中创建了一个文件,我从我的控制器中调用它。
def create
fn = params["firstname"]
ln = params["lastname"]
email = params["email"]
file = params["file"]
summery = params["summery"]
email_body = "Hello\n This is Your favorite website.\nA I want to personaly say hi."
WelcomeMailer.welcome(fn, ln, email, file, email_body).deliver_now
render json: {message: "An Email has been send", success: true}, status: 201
end
这是我的邮件
class WelcomeMailer < ActionMailer::Base
default from: "someone@yahoo.com"
def welcome(first_name, last_name, email, file, email_body)
attachments["#{file.original_filename}"] = File.read("#{file.tempfile.path}")
mail(
to: email,
subject: 'Welcome to My Awesome Site',
body: email_body
)
end
end
但是我仍然遇到同样的错误。
Errno::ECONNREFUSED - 连接被拒绝 - “localhost”端口 25 的连接(2):
回答
所以我找到了解决方案。是的,您需要使用 ActionMailer。之后,您需要转到config/environments/development.rb,并修改并添加以下行:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => "YOUR EMAIL",
:password => "YOUR Password",
:authentication => "plain",
:enable_starttls_auto => true
}
此外,如果 Gmail 抱怨此问题:
Net::SMTPAuthenticationError - 534-5.7.9 需要特定于应用程序的密码
转到此链接,让不太安全的应用程序访问 Gmail。
其他配置可用于雅虎等其他服务。只需谷歌它。