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

Joe*_*ano 0 ruby email automation ruby-on-rails ruby-on-rails-4

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>
Run Code Online (Sandbox Code Playgroud)

控制器:

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
Run Code Online (Sandbox Code Playgroud)

提前致谢!

moh*_*a27 5

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

  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  
}
Run Code Online (Sandbox Code Playgroud)
  1. 然后我们需要告诉Rails您要发送的电子邮件的具体信息,例如发送给谁的电子邮件,它来自哪里,以及实际的主题和内容.我们通过在最近创建的邮件程序中创建方法来做到这一点,

我们将其命名通知

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

  def notify(user)
    @user = user
    mail(to: @user.email,subject: "Notification")
  end
end
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)
  1. 最后,您可以通过以下方式发送邮件create:

运输方式:

UserMailer.notify(@user).deliver
Run Code Online (Sandbox Code Playgroud)

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

从此链接了解有关Mailers的更多信息