如何通过单击带有Rails的按钮发送自动电子邮件?

时间:2014-11-01 21:05:01

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

在提交表单时,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

提前致谢!

2 个答案:

答案 0 :(得分:5)

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

  1. 首先,您必须生成使用Rails生成命令的邮件程序:
  2.   

    rails生成邮件程序user_mailer

    1. 接下来要做的是为邮件程序设置SMTP传输。 在config/environments/development.rb文件中,添加以下配置:
    2. 这适用于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您要发送的电子邮件的具体内容,例如发送给谁的电子邮件,它来自哪里,以及实际的主题和内容。 我们通过在最近创建的邮件程序中创建方法来实现这一点,

      2. 我们将其命名为通知

        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. 最后,您可以通过以下方式发送邮件:{/ 1}}
        2. 送货方式:

          create

          请注意,您可以添加更多属性以将更多对象发送到方法UserMailer.notify(@user).deliver

          从此link

          了解有关Mailers的更多信息

答案 1 :(得分:1)

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

相关问题