Ruby on Rails - 发送电子邮件

Action Mailer 是 Rails 组件,可让应用程序发送和接收电子邮件。在本章中,我们将了解如何使用 Rails 发送电子邮件。让我们开始使用以下命令创建 emails 项目。

tp> rails new mailtest

这将创建继续操作所需的框架。现在,我们将开始配置 ActionMailer。

Action Mailer - 配置

在继续实际工作之前,您必须遵循以下步骤完成配置 −

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

config.action_mailer.delivery_method = :smtp

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

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

config.action_mailer.smtp_settings = {
   address:              'smtp.gmail.com',
   port:                 587,
   domain:               'example.com',
   user_name:            '<username>',
   password:             '<password>',
   authentication:       'plain',
   enable_starttls_auto: true  
}

用简单邮件传输协议 (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"。

下一步是创建邮件程序

生成邮件程序

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

tp> cd emails
emails> rails generate mailer Usermailer

这将在 app\mailer 目录中创建一个文件 user_mailer.rb。检查此文件的内容,如下所示 −

class Emailer < ActionMailer::Base
end

让我们创建一个方法,如下所示 −

class UserMailer < ApplicationMailer
   default from: 'notifications@example.com'
   
   def welcome_email(user)
      @user = user
      @url  = 'http://www.gmail.com'
      mail(to: @user.email, subject: 'Welcome to My Awesome Site')
   end
   
end
  • 默认哈希 − 这是您从此邮件程序发送的任何电子邮件的默认值哈希。在本例中,我们将 :from 标头设置为此类中所有消息的值。这可以根据每封电子邮件进行覆盖

  • 邮件 − 实际的电子邮件消息,我们将 :to 和 :subject 标头传入其中。

在 app/views/user_mailer/ 中创建一个名为 welcome_email.html.erb 的文件。这将是电子邮件使用的模板,采用 HTML 格式 −

<html>
   
   <head>
      <meta content = 'text/html; charset = UTF-8' http-equiv = 'Content-Type' />
   </head>
   
   <body>
      <h1>Welcome to example.com, <%= @user.name %></h1>
      
      <p>
         You have successfully signed up to example.com,your username is: 
         <%= @user.login %>.<br>
      </p>
      
      <p>
         To login to the site, just follow this link: 
         <%= @url %>.
      </p>
      
      <p>Thanks for joining and have a great day!</p>
      
   </body>
</html>

接下来我们将为该应用程序创建一个文本部分,如下所示 −

Welcome to example.com, <%= @user.name %>
===============================================
 
You have successfully signed up to example.com,
your username is: <%= @user.login %>.
 
To login to the site, just follow this link: <%= @url %>.
 
Thanks for joining and have a great day!

调用邮件程序

首先,让我们创建一个简单的用户脚手架

$ bin/rails generate scaffold user name email login
$ bin/rake db:migrate

Action Mailer 与 Active Job 完美集成,因此您可以在请求-响应周期之外发送电子邮件,这样用户就不必等待它 −

class UsersController < ApplicationController
   # POST /users
   # POST /users.json
   def create
   @user = User.new(params[:user])
   
      respond_to do |format|
         if @user.save
            # Tell the UserMailer to send a welcome email after save
            UserMailer.welcome_email(@user).deliver_later
            
            format.html { redirect_to(@user, notice: 'User was successfully created.') }
            format.json { render json: @user, status: :created, location: @user }
         else
            format.html { render action: 'new' }
            format.json { render json: @user.errors, status: :unprocessable_entity }
         end
         
      end
      
   end
end

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

发送电子邮件

这将发送您的消息并显示文本消息"消息发送成功"并输出如下 −

sent mail to kittuprasad700@gmail.com (2023.Sms)
[ActiveJob] [ActionMailler::DeliveryJob] [2cfde3c-260e-4a33-1a6ada13a9b] Date: Thu, 09 Jul 2015 11:44:05 +0530
From: notification@example.com
To: kittuprasad700@gmail.com
Message-Id: <559e112d63c57_f1031e7f23467@kiranPro.mail>
Subject: Welcome to My Awesome Site
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="--mimepart_559e112d601c8_f1031e7f20233f5";
charset=UTF-8
Content-Transfer-Encoding:7bit

有关如何使用 Rails 发送电子邮件的更多信息,请浏览 ActionMailer