如何在 Rails 6.1 中使用邮件程序?

Posted

技术标签:

【中文标题】如何在 Rails 6.1 中使用邮件程序?【英文标题】:How to use mailer in Rails 6.1? 【发布时间】:2021-09-15 03:12:10 【问题描述】:

我目前正在尝试创建一个联系我们的表单,用户可以在其中向我的个人电子邮件地址发送任何类型的报告。为了这个例子,我们称它为my-email-address@email.com

目前我不太关心用户的电子邮件。假设我将使用以下信息。

from:"my-email-address@email.com" to:"my-email-address@email.com" subject:"a subject name"

第 1 步:我在 views/home/contact_us.html.erb 中使用 AJAX POST 请求创建了我的表单:

<form id="sendEmailForm">
    <div class="form-group mb-3">
        <input type="email" class="form-control" id="exampleFormControlInput1" placeholder="Enter your email">
    </div>

    <div class="form-group mb-3">
        <input type="text" class="form-control" id="exampleFormControlInput2" placeholder="Enter a subject (Optional)">
    </div>

    <div class="form-group mb-3">
        <textarea class="form-control" placeholder="Please write your name, company-name, and what you would like to achieve." id="exampleFormControlTextarea3" rows="5"></textarea>
    </div>

    <button type="submit" class="btn btn-primary mb-2">Send Email</button>
</form>

<script type="text/javascript">

    $('#sendEmailForm').on('submit', function(e) 
        e.preventDefault();
        e.stopPropagation();

        let final_json_data = 
            email: document.getElementById("exampleFormControlInput1").value,
            subject: document.getElementById("exampleFormControlInput2").value,
            content: document.getElementById("exampleFormControlTextarea3").value
        ;

        jQuery.ajax(
            url: '/home/send_email_to_server',
            type: "POST",
            data: emailDetails: final_json_data,
            success: function(result)  
                alert("ajax request OK!");
            ,
            fail: function(result) 
                alert("ajax has failed")
            
        );  
    );
</script>

第 2 步:我的家庭控制器和 routes.rb:

class HomeController < ApplicationController

  def contact_us
    puts "GETTING THE PAGE !!!!!!!!!!!!!!!!!!!"
  end
  

  def send_email_to_server
    
    @emailDetails = params[:emailDetails]

    puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
    puts "     Store email details on server"

    puts @emailDetails['email']
    puts @emailDetails['subject']
    puts @emailDetails['content']
    puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"


    ContactUsMailer.notify_server_via_email(@emailDetails['email'], @emailDetails['subject']).deliver
  
    puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
    

  end
end
Rails.application.routes.draw do
  get 'home/contact_us'
  post 'home/send_email_to_server'
end

第 3 步: 修改 application_mailer.rb 以使用默认 from-email

class ApplicationMailer < ActionMailer::Base
    default from: "my-email-address@email.com"
    layout 'mailer'
end

第 4 步: 修改 contact_us_mailer.rb 以处理带有捕获参数的请求:

class ContactUsMailer < ApplicationMailer
    def notify_server_via_email(toEmail, aSubject)
        puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
        puts "     Trying to send an email . . . "

        @email = toEmail
        @subject = aSubject
        puts @email
        puts @subject

        puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"

        mail(
            to: @email,
            subject: @subject
        )
    end
end

第 4 步: 然后在views/contact_us_mailer 中创建了一个名为notify_server_via_email.html.erb 的新文件并添加了以下内容:

<h1> hello world </h1>

所以这是按顺序发生的:

    用户填写表单并提交按钮。 AJAX POST 请求到/home/send_email_to_server 服务器接收请求并捕获参数并执行mail()函数

但是我收到以下错误:

Started POST "/home/send_email_to_server" for ::1 at 2021-07-03 18:01:00 +0300
Processing by HomeController#send_email_to_server as */*
  Parameters: "emailDetails"=>"email"=>"my-email-address@email.com", "subject"=>"some new subject", "content"=>"a text example"



>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
     Store email details on server
my-email-address@email.com
some new subject
a text example
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>



>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
     Trying to send an email . . .
my-email-address@email.com
some new subject
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>



  Rendering layout layouts/mailer.html.erb
  Rendering contact_us_mailer/notify_server_via_email.html.erb within layouts/mailer
  Rendered contact_us_mailer/notify_server_via_email.html.erb within layouts/mailer (Duration: 0.5ms | Allocations: 70)
  Rendered layout layouts/mailer.html.erb (Duration: 1.5ms | Allocations: 241)
ContactUsMailer#notify_server_via_email: processed outbound mail in 14.0ms
Delivered mail 60e07bace69f9_27544024-497@DESKTOP-MQJ3IGG.mail (30045.8ms)
Date: Sat, 03 Jul 2021 18:01:00 +0300
From: my-email-address@email.com
To: my-email-address@email.com
Message-ID: <60e07bace69f9_27544024-497@DESKTOP-MQJ3IGG.mail>
Subject: some new subject
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
      /* Email styles need to be inline */
    </style>
  </head>

  <body>
    <h1> hello world </h1>
  </body>
</html>

Completed 500 Internal Server Error in 30095ms (ActiveRecord: 0.0ms | Allocations: 11373)



EOFError (end of file reached):

app/controllers/home_controller.rb:35:in `send_email_to_server'

我不知道是什么导致了 500 内部服务器错误。我目前在开发方面工作,我知道我不应该这样做,但这只是为了测试目的,我的目标不是永远保留这个配置。此外,我遇到了这个*** Question,这与我的问题相似,但没有明确的答案,因为那是大学 wifi 阻止 smtp 请求工作。我正在尝试使用家庭 wifi。

另外参考这里是我的development.rbaction_mailer 命令:

  config.action_mailer.perform_deliveries = true

  config.action_mailer.raise_delivery_errors = true

  config.action_mailer.delivery_method = :smtp

  config.action_mailer.smtp_settings = 
    :address => 'localhost',
    :port    => 3000
  

  config.action_mailer.default_url_options = host: 'localhost:3000'

  config.action_mailer.perform_caching = false

【问题讨论】:

【参考方案1】:

库net/protocol.rb#227 引发错误。如果您打开浏览器开发者工具,您可以在“网络”选项卡下状态为 500 的请求的子选项卡响应下看到它。

错误原因:库无法连接到根据您的development.rb 配置config.action_mailer.smtp_settings 位于localhost:3000 的smtp 服务器。您的网络服务器位于 3000 端口,smtp 通常位于 25、587、2525 端口(如果它正在运行)。

如果您希望在开发环境中向my-email-address@email.com 发送邮件,您需要在本地计算机上运行 smtp 服务器正确配置config.action_mailer.smtp_settings

如果您想查看电子邮件,可以查看控制台或日志。或者使用 gem letter_opener,或者使用ActionMailer::Preview。见answer at ***。

【讨论】:

以上是关于如何在 Rails 6.1 中使用邮件程序?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Sidekiq 在 Rails 中 3 分钟后发送电子邮件?

如何通过 Webpacker 使用 Rails 6.1 安装 Alpine JS 3

Rails 6.1 如何将文件渲染到页面模板中

如何使用 Rails 在 MongoDB 中验证跨模型的唯一性?

Rails, Devise, Postmark Gem - 使用邮戳模板设计邮件

如何修复弃用警告:类级别方法将不再继承 Rails 6.1 中的范围?