首页 > 解决方案 > 如何使用 Rails 发送电子邮件?

问题描述

我正在尝试在创建用户时发送电子邮件。我按照 Internet 上的说明进行操作,但是当我运行rails s并创建用户时,没有电子邮件发送到我的邮箱。有人知道为什么吗?我可以在我的 cmd 中看到如下消息,但我的邮箱应用程序中没有收到电子邮件:

Delivered mail 5e7a798d352b0_2ef0530c80914@xdh-virtual-machine.mail (2.7ms)
Date: Tue, 24 Mar 2020 17:20:13 -0400
From: daihaoxue1996@gmail.com
To: daihaoxue@yahoo.com
Message-ID: <5e7a798d352b0_2ef0530c80914@xdh-virtual-machine.mail>
Subject: Sample Email
Mime-Version: 1.0
Content-Type: multipart/alternative;
 boundary="--==_mimepart_5e7a798d2fa66_2ef0530c808c5";
 charset=UTF-8
Content-Transfer-Encoding: 7bit

下面是我的代码:ponies_controller:

  def create
    @pony = Pony.new(pony_params)

    respond_to do |format|
      if @pony.save
        ExampleMailer.sample_email(@pony).deliver
        format.html { redirect_to @pony, notice: 'Pony was successfully created.' }
        format.json { render :show, status: :created, location: @pony }
      else
        format.html { render :new }
        format.json { render json: @pony.errors, status: :unprocessable_entity }
      end
    end
  end

邮件程序/example_mailer.rb

class ExampleMailer < ApplicationMailer
  default from: "daihaoxue1996@gmail.com"

  def sample_email(user)
    @user = user
    mail(to: @user.email, subject: 'Sample Email')
  end

end

生产.rb

config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
 :address              => "smtp.gmail.com",
 :port                 => 587,
 :user_name            => "daihaoxue1996@gmail.com",
 :password             => "AAAAAAAAA",
 :authentication       => "plain",
:enable_starttls_auto => true
}

标签: ruby-on-rails

解决方案


推荐阅读