📜  ruby on rails 发送激活邮件 - Ruby (1)

📅  最后修改于: 2023-12-03 15:04:56.782000             🧑  作者: Mango

Ruby on Rails 发送激活邮件

在 Web 应用程序中,发送激活邮件是非常常见的需求。本文将介绍如何使用 Ruby on Rails 发送激活邮件的方法,涵盖以下内容:

  • 发送激活邮件的流程概述
  • 使用 Action Mailer 配置邮件发送器
  • 记录邮件发送历史
  • 自定义激活链接
  • 编写测试用例
发送激活邮件的流程概述

发送激活邮件的流程主要包括以下几个步骤:

  1. 注册用户
  2. 生成激活链接
  3. 将激活链接通过邮件发送给用户
  4. 用户点击激活链接并进行账户激活
  5. 记录账户激活状态和历史

下面我们逐一介绍如何实现以上流程。

使用 Action Mailer 配置邮件发送器

在使用 Ruby on Rails 发送激活邮件之前,我们需要先配置邮件发送器。Ruby on Rails 的默认邮件发送器是 Action Mailer。我们可以在 config/application.rb 文件中配置邮件发送器:

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address: 'smtp.gmail.com',
  port: 587,
  authentication: 'plain',
  user_name: 'your-gmail-username',
  password: 'your-gmail-password',
  enable_starttls_auto: true
}
config.action_mailer.default_url_options = { host: 'your-domain.com' }

以上配置使用了 Gmail 的 SMTP 服务器进行邮件发送。你需要将 your-gmail-usernameyour-gmail-password 替换成你自己的用户名和密码。同时,your-domain.com 也需要替换成你自己的域名。

记录邮件发送历史

为了方便调试和管理,我们需要记录邮件发送历史。可以新建一个 MailLog 模型,用于记录邮件发送历史。这里我们只记录邮件主题和收件人邮箱:

class MailLog < ApplicationRecord
  validates :subject, :to_email, presence: true
end

同时创建一个 MailLog 表,在 db/migrate 目录下创建一个新的迁移文件:

class CreateMailLogs < ActiveRecord::Migration[6.1]
  def change
    create_table :mail_logs do |t|
      t.string :subject
      t.string :to_email

      t.timestamps
    end
  end
end

执行迁移命令:

$ rails db:migrate
自定义激活链接

在生成激活链接之前,我们需要先在用户模型中添加一个字段 activated 用于记录用户账户是否已激活:

class User < ApplicationRecord
  attr_accessor :activation_token
  before_create :create_activation_digest

  def activate
    update_columns(activated: true, activated_at: Time.zone.now)
  end

  private

  def create_activation_digest
    self.activation_token = SecureRandom.urlsafe_base64
    self.activation_digest = BCrypt::Password.create(activation_token)
  end
end

其中,attr_accessor 用于添加一个虚拟属性 activation_token,方便后续生成激活链接使用。

在生成激活链接之前,我们需要引入 mail_helper 模块,用于生成 URL 中的 hostportprotocol

module MailHelper
  def default_url_options
    { host: Rails.application.config.action_mailer.default_url_options[:host] }
  end

  def url_for(options = nil)
    if options.is_a?(Hash) && options.has_key?(:protocol)
      super
    else
      super(options.merge(protocol: Rails.application.config.action_mailer.default_url_options[:protocol]))
    end
  end
end

接下来,在 user 模型中编写生成激活链接的方法:

class User < ApplicationRecord
  include MailHelper
  ...

  def activation_url
    url_for(controller: 'users', action: 'activate', token: activation_token)
  end
end

其中,activate 是我们新增的一个激活方法,token 是激活码,可以考虑在激活邮件中传入该参数。

编写测试用例

发送激活邮件是一个比较重要的功能,我们需要编写相关的测试用例来确保其正确性。可以在 spec/models/user_spec.rb 文件中新增以下测试用例:

require 'rails_helper'

RSpec.describe User, type: :model do
  ...

  describe '#send_activation_email' do
    let(:user) { create(:user) }
    let(:mail) { UserMailer.account_activation(user) }

    it 'sends an email' do
      expect { mail.deliver_now }.to change { ActionMailer::Base.deliveries.count }.by(1)
    end

    it 'renders the headers' do
      expect(mail.subject).to eq('Account Activation')
      expect(mail.to).to eq([user.email])
      expect(mail.from).to eq(['no-reply@example.com'])
    end

    it 'renders the body' do
      expect(mail.body.encoded).to match(user.activation_url)
    end
  end
end

以上测试用例中,我们创建了一个虚拟的 user 对象,并调用 UserMailer.account_activation(user) 方法生成后续需要发送的激活邮件 mail。我们分别测试了邮件的发送、主题、收件人和正文内容。

总结

通过以上程序员介绍,我们已经了解了如何使用 Ruby on Rails 发送激活邮件,以及如何配置邮件发送器、记录邮件发送历史、自定义激活链接和编写测试用例等细节。希望本文能对你有所帮助!