rails: 邮件发送/mail
使用 rails 发送邮件,QQ企业邮箱,aliyun 邮箱
背景
- 很多系统需要通知,邮件是个不错的选择
- 测试 qq 企业邮箱
测试端口
- QQ企业邮箱
- aliyun 企业邮箱
nc -zv smtp.exmail.qq.com 465
nc -zv smtp.exmail.qq.com 587这样表示通了
rails-smtp-mail on 🌱 main [!] via 💎 v3.3.6
$ nc -zv smtp.exmail.qq.com 465
Connection to smtp.exmail.qq.com port 465 [tcp/urd] succeeded!
rails-smtp-mail on 🌱 main [!] via 💎 v3.3.6
$ nc -zv smtp.exmail.qq.com 587
Connection to smtp.exmail.qq.com port 587 [tcp/submission] succeeded!最小化测试代码
require 'net/smtp'
# smtp.exmail.qq.com(使用SSL,端口号465)
# 测试 SMTP 连接
smtp_settings = {
address: 'smtp.exmail.qq.com',
port: 465,
user_name: 'admin@52doc.com',
password: 'abc123',
authentication: 'plain',
domain: '52doc.com'
}
begin
smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port])
smtp.enable_ssl # 明确启用 SSL
smtp.start(smtp_settings[:domain],
smtp_settings[:user_name],
smtp_settings[:password],
smtp_settings[:authentication]) do |smtp_conn|
puts "SMTP connection successful!"
end
rescue => e
puts "SMTP connection failed: #{e.message}"
puts "Backtrace: #{e.backtrace.first(5)}"
endRails 配置
- ./config/application.rb
config.action_mailer.delivery_method = :smtp
config.action_mailer.raise_delivery_errors = true
config.action_mailer.smtp_settings = {
address: 'smtp.exmail.qq.com',
port: 587,
user_name: 'admin@52doc.com',
password: ENV['SMTP_PASSWORD'],
authentication: 'plain',
enable_starttls_auto: true # 端口 587 使用 STARTTLS
}# 生成测试 mail
rails generate mailer UserMailer welcome_email
# mail 内容
class UserMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.user_mailer.welcome_email.subject
#
def welcome_email
@greeting = "Hi"
mail to: "1290657123@qq.com", subject: "Welcome to our website"
end
end
