如何在 ruby 中发送邮件

How to send mail in ruby

我有 heroku 帐户并在 heroku 上设置应用程序

网站工作正常,但只有邮件功能不工作我已经执行了以下代码。

class ContactMailer < ActionMailer::Base
  default from: "from@example.com"

  def sample_email()

    email = 'to@gmail.com'
    recipient = 'rec@gmail.com'
    subject = 'This is tesing '
    message = 'This is dummy mail'

    Emailer.deliver_contact(recipient, subject, message)
    return if request.xhr?
    render :text => 'Message sent successfully'

  end
end

设置邮件程序发送电子邮件

在app/mailers/user_mailer.rb

class UserMailer < ActionMailer::Mailer
  default from: "no-reply@myapp.com"

def welcome(user_email)
   @user=User.find_by_email user_email
   Rails.logger.info "==========sending welcome email to ==> #{@user.email}"
   mail(:to => @user.email, :subject => "Hi #{@user.username},Welcome to #{configatron.app_name}")
end
 end

设置视图文件作为电子邮件发送

app/views/user_emailer/welcome.html.erb

<p>Hi <%= @user.username %>,Welcome to myapp.com</p>

设置电子邮件配置

在config/initializers/email_setup.rb

if Rails.env != 'test'
  email_settings = YAML::load(File.open("#{Rails.root.to_s}/config/email.yml"))
  ActionMailer::Base.smtp_settings = email_settings[Rails.env] unless email_settings[Rails.env].nil?
end

设置 keys/passwords,使用 gmail.. 用于开发,但使用 mailchimp/mandrill 用于 pro

in config/email.yml

    development:
      :address: smtp.gmail.com
      :port: 587
      :authentication: plain
      :user_name: milind@gmail.com
      :password: password
      :enable_starttls_auto: true
    production:
      :address: smtp.gmail.com
      :port: 587
      :authentication: plain
      :user_name: milind@gmail.com
      :password: password
      :enable_starttls_auto: true

用于发送电子邮件的用户邮件程序

UserMailer.welcome(current_user).deliver

希望对您有所帮助.... :)