【问题标题】:How to send automatic emails with the click of a button with Rails?如何使用 Rails 单击按钮发送自动电子邮件?
【发布时间】:2014-12-28 20:52:02
【问题描述】:

Rails 中是否有办法在提交表单时自动发送一封电子邮件,其中包含来自该表单的信息?具体来说,我希望新用户在提交注册表单时收到一封包含他的新个人资料网址的电子邮件。

这是我的表单的样子:

<h1>Add Something!</h1>
<p>
  <%= form_for @thing, :url => things_path, :html => { :multipart => true } do |f| %>

    <%= f.text_field :name, :placeholder => "Name of the thing" %>
    <%= f.label :display_picture %>
    <%= f.file_field :avatar %>
    <br>
    <%= f.submit "Submit", class: "btn btn-primary" %>
  <% end %>
</p>

控制器:

class ThingsController < ApplicationController

  def show
    @thing = Thing.find(params[:id])
  end

  def new
    @thing = Thing.new
    @things = Thing.all
  end

  def create
    @thing = Thing.new(thing_params)
    if @thing.save
      render :action => "crop"     
    else
      flash[:notice] = "Failed"
      redirect_to new_things_path
    end
  end

  private

    def thing_params
      params.require(:thing).permit(:name, :avatar)
    end

end

提前致谢!

【问题讨论】:

  • 你有邮件对象吗?
  • @SamD 我不确定那是什么。

标签: ruby-on-rails ruby email ruby-on-rails-4 automation


【解决方案1】:

假设我们需要在创建操作时通知用户。

  1. 首先你必须生成你的邮件,它使用 Rails 生成命令:

rails 生成邮件程序 user_mailer

  1. 接下来要做的是为您的邮件程序设置 SMTP 传输。 在config/environments/development.rb文件中,添加如下配置:

这是给 gmail 的,(输入您的域名、用户名和密码):

config.action_mailer.delivery_method = :smtp 
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  
}
  1. 然后我们需要告诉 Rails 你想要发送的电子邮件的细节,比如发送给谁,它来自哪里,以及实际的主题和内容。 我们通过在最近创建的邮件程序中创建一个方法来做到这一点,

我们将其命名为 notify

class UserMailer < ActionMailer::Base
  default from: 'notification@example.com'

  def notify(user)
    @user = user
    mail(to: @user.email,subject: "Notification")
  end
end

4. 在 app/views/user_mailer/ 中创建一个名为 notify.html.erb 的文件。这将是用于电子邮件的模板,格式为 html.erb:

这是您可以发送的内容:

<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 received a notification
    </p>
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>
  1. 最后,您可以通过以下方式在create 操作中发送邮件:

发货方式:

UserMailer.notify(@user).deliver

请注意,您可以添加更多属性以将更多对象发送到方法notify

通过link了解更多关于邮件的信息

【讨论】:

    【解决方案2】:

    查看ActionMailer::Base 类以及这个名为Letter Opener 的酷宝石,它将在测试时为您提供帮助,因为它会在浏览器中打开已发送的电子邮件。

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 2013-12-31
      • 1970-01-01
      相关资源
      最近更新 更多