Ruby on Rails - 傳送郵件



Action Mailer 是 Rails 元件,它使應用程式能夠傳送和接收電子郵件。 在本章中,我們將瞭解如何使用 Rails 傳送電子郵件。 讓我們開始使用以下命令建立 emails 專案。

tp> rails new mailtest

這將建立所需的框架以繼續進行。 現在,我們將開始配置 ActionMailer。

Action Mailer - 配置

以下是在繼續實際工作之前必須遵循的步驟 -

轉到 emails 專案的 config 資料夾並開啟 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) 伺服器的正確設定。 如果您還不知道,您可以從您的網際網路服務提供商處獲取此資訊。 如果您使用的是標準 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
  • default Hash - 這是您從此郵件程式傳送的任何電子郵件的預設值的雜湊。 在這種情況下,我們正在將 :from 標頭設定為此類中所有訊息的值。 這可以在每個電子郵件的基礎上被覆蓋

  • mail - 實際的電子郵件訊息,我們正在傳遞 :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 測試您的應用程式。 它顯示以下螢幕,並使用此螢幕,您將能夠向任何人傳送您的訊息。

Send Email

這將傳送您的訊息,並將顯示文字訊息“訊息傳送成功”並輸出如下 -

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

廣告

© . All rights reserved.