【山竹记账后端】7.用 Rails Mailer 和 QQ邮箱发邮件


大纲链接 §

[toc]


1. 选择发邮件 ⇧

选择邮件 v.s. 手机短信

  • 短信在国内收费较高,但是邮件可以免费
  • 展示项目,邮箱登录方式防止隐私泄露
  • Rails 内置邮件功能

搜索文档


开发前确保代码都已提交;下面开始演示如何用 Rails + QQ邮箱发邮件

2. 创建 Mailer ⇧

  • 使用脚手架命令 bin/rails generate mailer User

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    bin/rails generate mailer User
    
    # 自动创建
    create  app/mailers/user_mailer.rb
    invoke  erb
    create    app/views/user_mailer
    invoke  rspec
    create    spec/mailers/user_mailer_spec.rb
    create    spec/mailers/previews/user_mailer_preview.rb

参考


3. 在全局配置 ApplicationMailer ⇧

app/mailers/application_mailer.rb

1
2
3
4
class ApplicationMailer < ActionMailer::Base
  default from: "from@example.com"
  layout "mailer"
end
  • 将邮箱配置成自己发送邮件的邮箱
  • 其中 layout "mailer" 是邮件默认html布局,在 app/views/layouts/mailer.html.erb

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style>
      /* Email styles need to be inline */
    </style>
    <title>hi</title>
    </head>
    
    <body>
    <%= yield %>
    </body>
    </html>
  • 其中 <%= yield %> 的内容是在 app/views/user_mailer/welcome_email.html.erb

    1
    
    <p>hi</p>
  • 修改为任意内容,格式为 html

app/mailers/user_mailer.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class UserMailer < ApplicationMailer
  # 已在全局默认配置过了,可以做到随时修改
  # default from: "notifications@example.com"

  def welcome_email
    @user = params[:user]
    @url  = "http://example.com/login"
    # mail(to: @user.email, subject: "Welcome to My Awesome Site")
    mail(to: "xxx@example.com", subject: "Welcome to My Awesome Site")
  end
end
  • 主要逻辑可写死发送邮件到自己的邮箱 mail(to: "xxx@example.com", subject: "Hi")

创建邮件内容 app/views/user_mailer/welcome_email.html.erb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <title>Welcome to my website</title>
  </head>
  <body>
    hi
  </body>
</html>

4. 配置邮件服务器 ⇧

暂时只在开发环境配置 config/environments/development.rb

  • 仅作测试用,生产环境需要单独的用户名和密码
  • 文件内搜索 mailer

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    
    require "active_support/core_ext/integer/time"
    
    Rails.application.configure do
    # ...
    # Don't care if the mailer can't send.
    config.action_mailer.raise_delivery_errors = true
    
    # Disable caching for Action Mailer templates even if Action Controller
    # caching is enabled.
    config.action_mailer.perform_caching = false
    
    config.action_mailer.default_url_options = { host: "localhost", port: 3000 }
    
    # ...
    end
  • config.action_mailer.raise_delivery_errors 是否抛出发送时的错误,需要开启

  • 后面两项无所谓配置

尝试发送邮件

  • 启动命令行 bin/rails console
  • 发送失败:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    
    bin/rails console
    # Loading development environment (Rails 7.2.3.2)
    # 3.1.2 :001 >
    
    UserMailer.welcome_email.deliver
    
    # 回车,发送失败
    #   Rendering layout layouts/mailer.html.erb
    #   Rendering user_mailer/welcome_email.html.erb within layouts/mailer
    #   Rendered user_mailer/welcome_email.html.erb within layouts/mailer (Duration:...)
    #   Rendered layout layouts/mailer.html.erb (Duration: 1.5ms | GC: 0.0ms)
    # UserMailer#welcome_email: processed outbound mail in 23.3ms
    # Failed delivery of mail 6afeff9b1499e_20fbad9844874@a3b047027c2c.mail
    #  error_class=Errno::ECONNREFUSED error_message="Connection refused - connect(2)"
    # Date: Thu, 19 Nov 2026 21:54:35 +0800
    # From: xxx@163.com
    # To: xxx@163.com
    # Message-ID: <6afeff9b1499e_20fbad9844874@a3b047027c2c.mail>
    # Subject: Welcome to My Awesome Site
    # MIME-Version: 1.0
    # Content-Type: text/html;
    #  charset=UTF-8
    # Content-Transfer-Encoding: 7bit
    
    # <!-- BEGIN app/views/layouts/mailer.html.erb --><!DOCTYPE html>
    # <html>
    #   <head>
    #     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    #     <style>
    #       /* Email styles need to be inline */
    #     </style>
    #   </head>
    
    #   <body>
    #     <!-- BEGIN app/views/user_mailer/welcome_email.html.erb --><!DOCTYPE html>
    # <html>
    #   <head>
    #     <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    #     <title>Welcome to my website</title>
    #   </head>
    #   <body>
    #     hi
    #   </body>
    # </html><!-- END app/views/user_mailer/welcome_email.html.erb -->
    #   </body>
    # </html>
    # <!-- END app/views/layouts/mailer.html.erb -->
    # (mangosteen1):1:in `<main>': Connection refused - connect(2) for...

运行命令 EDITOR="code --wait" rails credentials:edit 生成密钥文件 config/credentials.yml.enc

1
2
3
4
5
6
7
# aws:
#   access_key_id: 123
#   secret_access_key: 345

# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: xxxxxxx
email_password: xxxxxx

添加邮箱服务配置 config/environments/development.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
require "active_support/core_ext/integer/time"

Rails.application.configure do
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_caching = false
  config.action_mailer.default_url_options = { host: "localhost", port: 3000 }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address:         "smtp.qq.com",
    port:            587,
    domain:          "smtp.qq.com",
    user_name:       "xxx@qq.com",
    password:        Rails.application.credentials.email_password,
    authentication:  "plain",
    enable_starttls: true,
    open_timeout:    10,
    read_timeout:    10 }
end
  • email_password 映射的是邮箱生成的 POP3/IMAP/SMTP/Exchange/CardDAV 服务生成的授权码
  • 确保此处 user_name
    • 和 user_mailer.rb 中设置的 default from: "xxx@example.com" 一致
    • 或者和 app/mailers/application_mailer.rb 中设置的 default from: "xmasuhai@qq.com" 一致
  • 再次使用控制台 bin/rails c 运行 UserMailer.welcome_email.deliver

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    
    bin/rails console
    # Loading development environment (Rails 7.2.3.2)
    # 3.1.2 :001 >
    
    UserMailer.welcome_email.deliver
    
    #   Rendering layout layouts/mailer.html.erb
    #   Rendering user_mailer/welcome_email.html.erb within layouts/mailer
    #   Rendered user_mailer/welcome_email.html.erb within layouts/mailer (Duration: 0.3ms | GC: 0.0ms)
    #   Rendered layout layouts/mailer.html.erb (Duration: 0.7ms | GC: 0.0ms)
    # UserMailer#welcome_email: processed outbound mail in 9.3ms
    # Delivered mail 6affdec98decf_5c7bd98696dc@ffd593e1ac60.mail (965.6ms)
    # Date: Fri, 20 Nov 2026 13:46:49 +0800
    # From: xxx@qq.com
    # To: xxx@163.com
    # Message-ID: <6affdec98decf_5c7bd98696dc@ffd593e1ac60.mail>
    # Subject: Welcome to My Awesome Site
    # MIME-Version: 1.0
    # Content-Type: text/html;
    #  charset=UTF-8
    # Content-Transfer-Encoding: 7bit
    #
    # <!-- BEGIN app/views/layouts/mailer.html.erb --><!DOCTYPE html>
    # <html>
    #   <head>
    #     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    #     <style>
    #       /* Email styles need to be inline */
    #     </style>
    #   </head>
    #
    #   <body>
    #     <!-- BEGIN app/views/user_mailer/welcome_email.html.erb --><!DOCTYPE html>
    # <html>
    #   <head>
    #     <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    #     <title>Welcome to my website</title>
    #   </head>
    #   <body>
    #     hi
    #   </body>
    # </html><!-- END app/views/user_mailer/welcome_email.html.erb -->
    #   </body>
    # </html>
    # <!-- END app/views/layouts/mailer.html.erb -->
    => #<Mail::Message:12120, Multipart: false, Headers: <Date: Fri, 20 Nov 2026 13:46:49 +0800>, <From: xxx@qq.com>, <To: xxx@163.com>, <Message-ID: <6affdec98decf_5c7bd98696dc@ffd593e1ac60.mail>>, <Subject: Welcome to My Awesome Site>, <MIME-Version: 1.0>, <Content-Type: text/html>, <Content-Transfer-Encoding: 7bit>>
  • 即发送成功,查看邮箱是否已收取到邮件

参考


5. 发送邮件传参验证码 code ⇧

app/mailers/user_mailer.rb

1
2
3
4
5
6
class UserMailer < ApplicationMailer
  def welcome_email(code)
    @code = code
    mail(to: "xmasuhai@qq.com", subject: "hi")
  end
end

app/views/user_mailer/welcome_email.html.erb

1
<p>验证码: <%= @code %></p>
  • 注意占位符 <%= @code %>
  • bin/rails c 进入控制台,使用控制台发送 UserMailer.welcome_email('123456').deliver
  • 发送后查看是否收到邮件

6. Rails 应用重新创建密钥 ⇧

创建密钥分两种情况:

  • 如果你想保留之前创建的 config/master.key 和 config/credentials.yml.enc 两个文件
    • 就直接把之前的文件复制到本项目的 config 里。
  • 如果你之前没有创建过 config/master.key 和 config/credentials.yml.enc 两个文件,就按下面的步骤做:

    1
    2
    
    rm config/credentials.yml.enc
    EDITOR="code --wait" rails credentials:edit
  • 注意,如果是生产环境,你就在 credentials:edit 后面加上 --environment production 参数

  • 然后,在打开的文件中写入如下内容(其中 xxx 应该是一串密码或者一串随机字符串,具体怎么生成 xxx 要看对应的视频,不记得就回看一下自己的笔记):

    1
    2
    3
    
    secret_key_base: xxx
    email_password: xxx
    hmac_secret: xxx
  • 这样,就得到了 config/master.key 和config/credentials.yml.enc 两个文件

  • 此时应该提交代码。然后开始写新的代码


7. 总结 ⇧

  • 创建 Mailer 相关文件,命令 bin/rails generate mailer User 自动生成文件
  • 全局配置 app/mailers/application_mailer.rb,发送邮箱改为 default from: "from@example.com"
  • 邮件内容模板 app/views/user_mailer/welcome_email.html.erb
  • 在第三方邮箱服务中设置授权码,将授权码保存到 config/credentials.yml.enc email_password: xxxx
  • 开发环境配置邮件服务器 config/environments/development.rb
    • 添加配置 config.action_mailer.smtp_settings
    • 设置好邮件服务地址、端口 587、用户名邮箱、超时时间等
    • 设置好密码 password: Rails.application.credentials.email_password
  • 修改 app/mailers/user_mailer.rb 中方法传参 def welcome_email(code) @code = code ... end
  • 使用控制台临时发送验证:bin/rails c 命令 UserMailer.welcome_email('123456').deliver

·未完待续·

参考文章

  • 代码
  • 拿到代码后,你可能需要重新创建密钥:文档
  • 这一步是可选的,但如果你遇到 ActiveSupport::MessageEncryptor::InvalidMessage 报错,那么你就必须重新创建密钥了
  • 添加密码的命令是 EDITOR="code --wait" bin/rails credentials:edit
    • 在新文件中写入 email_password: xxx
    • 然后在 Rails 中使用 Rails.application.credentials.email_password 获取对应的值

相关文章

  • 无

  • 作者: Joel
  • 文章链接:
  • 版权声明
  • 非自由转载-非商用-非衍生-保持署名