首页
/ MailForm 技术文档

MailForm 技术文档

2024-12-23 12:43:48作者:蔡怀权

本文档旨在帮助用户详细了解并使用 MailForm 项目。以下是项目的安装指南、使用说明、API 使用文档和安装方式的详细介绍。

1. 安装指南

在项目中使用 MailForm 前,需要进行以下安装步骤:

首先,将以下内容添加到 Gemfile 中:

gem 'mail_form'

然后,执行以下命令安装 MailForm:

bundle install

安装完成后,可以使用 rails generate mail_form 命令获取关于生成基本表单的帮助信息。

2. 项目的使用说明

MailForm 是基于 ActiveModel 构建的,允许您从表单直接发送电子邮件。以下是如何在 Rails 5+ 中使用 MailForm 的示例:

创建一个继承自 MailForm::Base 的类:

class ContactForm < MailForm::Base
  attribute :name, validate: true
  attribute :email, validate: /\A[^@\s]+@[^@\s]+\z/i
  attribute :file, attachment: true

  attribute :message
  attribute :nickname, captcha: true

  def headers
    {
      subject: "My Contact Form",
      to: "your.email@your.domain.com",
      from: %("#{name}" <#{email}>)
    }
  end
end

然后,在 Rails 控制台中创建一个实例并发送电子邮件:

c = ContactForm.new(name: 'José', email: 'jose@email.com', message: 'Cool!')
c.deliver

确保已正确配置邮件发送方法。

3. 项目API使用文档

以下是 MailForm 的 API 概述:

attributes(*attributes)

声明表单属性。声明的所有属性将附加到电子邮件中,除了 :captcha 为 true 的属性。

选项:

  • :validate - 验证钩子,用于 validates_*_of。当给定 true 时,验证属性的存在。当给定正则表达式时,验证格式。当给定数组时,验证属性是否包含在数组中。

  • :attachment - 当给定,期望发送文件并将其附加到电子邮件中。不要忘记将表单设置为多部分类型。

  • :captcha - 当为 true 时,验证属性必须为空。这是一种简单的方法来避免垃圾邮件,输入应该使用 CSS 隐藏。

示例:

class ContactForm < MailForm::Base
  attributes :name, validate: true
  attributes :email, validate: /\A[^@\s]+@[^@\s]+\z/i
  attributes :type, validate: ["General", "Interface bug"]
  attributes :message
  attributes :screenshot, attachment: true, validate: :interface_bug?
  attributes :nickname, captcha: true

  def interface_bug?
    if type == 'Interface bug' && screenshot.nil?
      self.errors.add(:screenshot, "can't be blank on interface bugs")
    end
  end
end

append(*methods)

MailForm 还可以轻松地附加来自客户端的请求信息到发送的邮件中。只需这样做:

class ContactForm < MailForm::Base
  append :remote_ip, :user_agent, :session
  # ...
end

在控制器中:

@contact_form = ContactForm.new(params[:contact_form])
@contact_form.request = request

远程 IP、用户代理和会话信息将随邮件发送,在邮件中的一个请求信息部分。你可以附加任何请求对象响应的方法。

4. 项目安装方式

MailForm 的安装方式已在上述 "安装指南" 部分进行了说明。简要概括,只需将 MailForm 添加到 Gemfile 中,然后运行 bundle install 命令即可完成安装。

通过以上内容,用户应能够成功安装并使用 MailForm,以及理解其 API 的基本用法。

登录后查看全文
热门项目推荐