Actionmailer 验证发送的最大电子邮件

Actionmailer validate maximum email sent

我希望用户每天发送的电子邮件不超过 5 封。可以验证吗?

user_mailer.rb

class UserMailer < ActionMailer::Base
  def contact_email(from_email, body, to_email)
     @body = body

     @user = User.find_by(email: to_email)
     mail(from: from_email, to: to_email, subject: '', cc: from_email)
  end
end

users_controller.rb

def send_mail
  @user = User.find(params[:id])
  @body = params[:message]

  UserMailer.contact_email(current_user.email, @body, @user.email).deliver_now
end

您可以使用 user_idcreated_at 创建模型 SentMail

修改您的 User 模型以包含 has_many :sent_mails

然后修改你的send_mail方法如下。

def send_mail
  @user = User.find(params[:id])
  @body = params[:message]
  if @user.sent_mails.last_day.count < 5
    UserMailer.contact_email(current_user.email, @body, @user.email).deliver_now
    @user.sent_mails.create
  end
end

在您的 SentMail 模型中创建范围 last_day 以创建以下查询 where(created_at: 24.hours.ago..DateTime.now.utc)

SentMail 模型也是跟踪发送的电子邮件的好方法,如果您想存储电子邮件的打开、发送、点击等状态,这会很好。