Ruby on Rails 2.1 - 发送电子邮件

ActionMailer 是 Rails 组件,可让应用程序发送和接收电子邮件。在本章中,我们将了解如何使用 Rails 发送电子邮件。

让我们先使用以下命令创建一个 emails 项目。

C:
uby> rails -d mysql emails

这里我们使用 -d mysql 选项来指定我们感兴趣的 MySQL 数据库。我们可以使用 -d 选项指定任何其他数据库名称,如 oraclepostgress。默认情况下,Rails 使用 SQLite 数据库。

设置数据库

尽管我们在应用程序中没有使用数据库,但 Rails 需要它才能继续运行。所以让我们执行这些额外的步骤。

下面给出了创建数据库的方法 −

mysql> create database emails;
Query OK, 1 row affected (0.01 sec)

mysql> grant all privileges on emails.*
 to 'root'@'localhost' identified by 'password';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

要指示 Rails 查找数据库,请编辑配置文件 ~\upload\config\database.yml 并将数据库名称更改为 cookbook。完成后,它应如下所示−

development:
   adapter: mysql
   encoding: utf8
   database: emails
   username: root
   password: password
   host: localhost
test:
   adapter: mysql
   encoding: utf8
   database: emails
   username: root
   password: password
   host: localhost
production:
   adapter: mysql
   encoding: utf8
   database: emails
   username: root
   password: password
   host: localhost

Action Mailer – 配置

在进行实际工作之前,您必须遵循以下步骤来完成配置。 −

转到电子邮件项目的配置文件夹,打开 environment.rb 文件,并在该文件底部添加以下行。

ActionMailer::Base.delivery_method = :smtp

它通知 ActionMailer 您想要使用 SMTP 服务器。如果您使用的是基于 Unix 的操作系统(例如 Mac OS X 或 Linux),您也可以将其设置为 :sendmail。

在您的 environment.rb 底部也添加以下代码行。

ActionMailer::Base.smtp_settings = {
   :address => "smtp.tutorialspoint.com",
   :port => 25,
   :domain => "tutorialspoint.com",
   :authentication => :login,
   :user_name => "username",
   :password => "password",
}

用简单邮件传输协议 (SMTP) 服务器的适当设置替换每个哈希值。如果您还不知道,可以从 Internet 服务提供商处获取此信息。如果您使用的是标准 SMTP 服务器,则无需更改端口号 25 和身份验证类型。

您还可以更改默认电子邮件格式。如果您希望以 HTML 而不是纯文本格式发送电子邮件,请将以下行也添加到 config/environment.rb −

ActionMailer::Base.default_content_type = "text/html"

ActionMailer::Base.default_content_type 可以设置为"text/plain"、"text/html"和"text/enriched"。默认值为"text/plain"。

下一步是创建邮件程序。

生成邮件程序

使用以下命令生成邮件程序,如下所示 −

C:
uby\> cd emails
C:
uby\emails> ruby​​ script/generate mailer Emailer

它将在 app/models 目录中创建一个文件 emailer.rb。检查此文件的内容如下 −

class Emailer < ActionMailer::Base
end

现在让我们在 ActionMailer::Base 类中创建一个方法,如下所示 −

class Emailer < ActionMailer::Base
   def contact(recipient, subject, message, sent_at = Time.now)
      @subject = subject
      @recipients = recipient
      @from = 'no-reply@yourdomain.com'
      @sent_on = sent_at
      @body["title"] = 'This is title'
      @body["email"] = 'sender@yourdomain.com'
      @body["message"] = message
      @headers = {}
   end
end

联系方法有四个参数:收件人、主题、消息和 sent_at,后者定义电子邮件的发送时间。该方法还定义了六个标准参数,它们是每个 ActionMailer 方法的一部分 −

  • @subject 定义电子邮件主题。

  • @body 是一个 Ruby 哈希,其中包含可用于填充邮件模板的值。您创建了三个键值对:标题、电子邮件和消息

  • @recipients 是要向其发送消息的人员列表。

  • @from 定义电子邮件的发件人。

  • @sent_on 采用 sent_at 参数并设置电子邮件的时间戳。

  • @headers 是另一个哈希,可用于修改电子邮件标题。例如,如果您想发送纯文本或 HTML 电子邮件,则可以设置电子邮件的 MIME 类型。

创建控制器

现在,我们将为此应用程序创建一个控制器,如下所示 −

C:
uby\emails> ruby​​ script/generate controller Emailer

让我们在 app/controllers/emailer_controller.rb 中定义一个控制器方法 sendmail,它将调用 Model 方法发送实际电子邮件,如下所示 −

class EmailerController < ApplicationController
   def sendmail
      recipient = params[:email]
      subject = params[:subject]
      message = params[:message]
      Emailer.deliver_contact(recipient, subject, message)
      return if request.xhr?
      render :text => 'Message sent successfully'
   end
end

要使用邮件程序的联系方法发送电子邮件,您必须在方法名称的开头添加 deliver_。添加 return if request.xhr?,这样如果浏览器不支持 JavaScript,您就可以转为使用 Rails Java Script (RJS),然后指示该方法呈现文本消息。

您几乎已经完成了,只需准备一个屏幕,您将从该屏幕获取发送电子邮件的用户信息。让我们在控制器中定义一个屏幕方法索引,然后在下一节中,我们将定义所有必需的视图 −

在 emailer_controller.rb 文件中添加以下代码。

def index
   render :file => 'app\views\emailer\index.html.erb'
end

定义视图

在 app\views\emails\index.html.erb 中定义一个视图。这将被称为应用程序的默认页面,并允许用户输入消息并发送所需的电子邮件 −

<h1>Send Email</h1>
<% form_tag :action => 'sendmail' do %>
<p><label for="email_subject">Subject</label>:
<%= text_field 'email', 'subject' %></p>
<p><label for="email_recipient">Recipient</label>:
<%= text_field 'email', 'recipient' %></p>
<p><label for="email_message">Message</label><br/>
<%= text_area 'email', 'message' %></p>
<%= submit_tag "Send" %>
<% end %>

除了上述视图之外,我们还需要另一个模板,它将由 Emailer 的联系方法在发送消息时使用。这只是带有标准 Rails <%= %> 占位符的文本。

只需将以下代码放入 app/views/contact.html.erb 文件中即可。

Hi!
You are having one email message from <%= @email %> with a title 
<%= @title %>
and following is the message:
<%= @message %>
Thanks

测试前的准备

在测试之前,请确保您的机器已连接到互联网,并且您的电子邮件服务器和 Web 服务器已启动并正在运行。

现在,使用 http://127.0.0.1:3000/Emailer/index 测试您的应用程序。它显示以下屏幕,通过此屏幕,您将能够向任何人发送消息。

发送电子邮件

发送消息后,它将显示文本消息 - "消息已成功发送"。

使用 Rails 发送 HTML 电子邮件

要以 HTML 格式发送邮件,请确保您的视图(.erb 文件)生成 HTML,并在您的 emails/app/models/emailer.rb 文件中将内容类型设置为 html,如下所示 −

class Emailer < ActionMailer::Base
   def contact(recipient, subject, message, sent_at = Time.now)
      @subject = subject
      @recipients = recipient
      @from = 'no-reply@yourdomain.com'
      @sent_on = sent_at
      @body["title"] = 'This is title'
      @body["email"] = 'sender@yourdomain.com'
      @body["message"] = message
      @headers = {content_type => 'text/html'}
   end
end

有关 ActionMailer 的完整详细信息,请参阅标准 Ruby 文档。