简体   繁体   English

在Rails中使用ActionMailer接收来自表单的电子邮件

[英]Using ActionMailer in Rails to receive emails from forms

I am trying to receive emails from a Contact Form using ActionMailer in Rails 5. But I am not sure on how send the params of the resource created on the form to the email on the receive method and send it to the email of the app. 我正在尝试使用Rails 5中的ActionMailer从联系表单中接收电子邮件,但是我不确定如何将在表单上创建的资源的参数发送到receive方法中的电子邮件,然后将其发送到应用程序的电子邮件中。

controllers/contacts_controller.rb: 控制器/ contacts_controller.rb:

class ContactsController < ApplicationController

  def index
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(contact_params)
    if @contact.save
      DefaultMailer.receive(@contact).deliver
      redirect_to root_path
    else
      render :new
    end
  end

  private
  def contact_params
    params.require(:contact).permit(:name, :email, :subject, :body)
  end
end

mailers/default_mailer.rb: 邮寄/ default_mailer.rb:

class DefaultMailer < ApplicationMailer
  default from: "atendimento@lcasystems.com.br"

  def receive(email)
    mail.create(subject: email.subject, body: email.body)
  end
end

It gives a 500 server error and says undefined method `humanize' for nil:NilClass in the receiver method. 它给出了500个服务器错误,并在接收方方法中为nil:NilClass说了未定义的方法'humanize'。

It's a contact form, so you want the email to be sent to yourself, so you need the to: key-value pair. 这是一个联系表单,因此您希望将电子邮件发送给自己,因此需要“ to:键-值”对。

It's also useful to include the contact's name and email so you can know where to send any replies. 包括联系人的姓名和电子邮件也很有用,这样您就可以知道将答复发送到哪里。

def receive(contact)
  mail(to: "atendimento@lcasystems.com.br", 
       subject: contact.subject, 
       body: contact.body.to_s + 
            "\n (Sender is #{contact.name} and their email is #{contact.email})")
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM