如何在ruby中发送邮件

时间:2015-05-18 17:23:21

标签: ruby-on-rails ruby email actionmailer

我有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

1 个答案:

答案 0 :(得分:0)

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

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

设置密钥/密码,使用gmail ...进行开发,但使用mailchimp / mandrill作为专业人士

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

希望它能帮助.... :)