【问题标题】:Rails send mail with gmail development modeRails用gmail开发模式发送邮件
【发布时间】:2015-09-02 09:09:08
【问题描述】:

我不知道如何在开发环境中从 gmail 发送邮件。它没有发送电子邮件。我没看懂rails guide,我也想知道生产环境是不是一样的?

config/development.rb

config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { :host => 'something.com' } 
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address:              'smtp.gmail.com',
port:                 587,
domain:               'mail.google.com',
user_name:            'myusername@gmail.com',
password:             'mypassword',
authentication:       'plain',
enable_starttls_auto: true  }

mailer/user_mailer.rb

 default :from => 'something.com'

 def welcome_email(user)
   @user = user
   @url  = 'http://something.com'
   mail(to: @user.email, subject: 'Welcome')
 end

编辑

我调用的地方,在用户创建方法中,

UserMailer.welcome_email(@user).deliver_now

【问题讨论】:

  • 你从哪里打电话给邮件?
  • 我会更新的
  • 所以没有错误?日志中有什么内容?
  • 在此处更新您的错误日志。谢谢
  • 没有错误,我成功创建了用户,但是邮件没有发送

标签: ruby-on-rails sendmail


【解决方案1】:
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true

development.rb 试试这个,它会发送邮件或在控制台中引发投递错误。

【讨论】:

  • 我正在寻找运行服务器的控制台
  • 试试这个UserMailer.welcome_email(@user).deliver_now!
  • 这次报错了,无法连接,因为目标机器主动拒绝。 - 连接(2)“本地主机”端口 25
  • 将 smtp_settings 中的域选项更改为 domain: "gmail.com" 它会为您工作。
  • 尝试重启服务器。谢谢
【解决方案2】:

您可以通过两种方式调用您的邮件方法来发送电子邮件,

  1. UsersControllercreate 操作中

    def create
        #your codes and logics to save user...
        UserMailer.welcome_email(@user).deliver_now
        #your codes goes here ...  
    end  
    
  2. User模型after_create回调中

     class User < ActiveRecord::Base
       after_create :send_email
    
       def send_email
          UserMailer.welcome_email(self).deliver_now
       end  
     end
    

我更喜欢第二个发送电子邮件,使用模型回调而不是在控制器中。

【讨论】:

  • 第二个会报错,undefined method `email' for nil:NilClass
  • Edited @use 越来越为零,我复制了你的代码并忘记在模型中替换 @user,因为它在这里不可用,self 发送和用户对象,它应该有 email。立即尝试。
  • 什么都没有发生,但是当我尝试 deliver.now! 时,我收到错误 由于目标机器主动拒绝,无法建立连接。 - 连接(2)“本地主机”端口 25
  • 您的问题是您应该从哪里发送电子邮件,对吗?这是发送电子邮件的方式。现在问题出在你smtp 不允许接收电子邮件。在您的配置中尝试另一个端口,例如 465 和 25,检查哪个有效。
  • 我重启了服务器,现在问题不一样了,534-5.7.9 需要应用程序专用密码。了解更多信息,请访问
猜你喜欢
  • 2011-02-16
  • 2012-08-29
  • 1970-01-01
  • 2011-06-28
  • 1970-01-01
  • 2011-11-24
  • 2014-12-05
  • 2014-12-06
  • 1970-01-01
相关资源
最近更新 更多