#020 How to send emails in Rails

| 21 minutes | 入门
介绍如何在Rails中发送Email.

在console中创建mailer

rails g mailer CommentMailer

Mailer代码,

app/mailers/comment_mailer.rb
class CommentMailer < ActionMailer::Base
  default from: "poshboytl@gmail.com"

  def comment_notify_email(comment)
    @comment = comment
    @url = post_url(@comment.post, host: 'localhost')

    mail to: 'poshboytl@gmail.com', subject: 'There is a new comment on your blog'
  end
end

Mail View

app/views/comment_mailer/comment_notify_email.html.erb
<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
  </head>
  <body>
    <h1>There is a new comment on your blog</h1>
    <p> <%= @comment.content %></p>
    <p> url: <%= @url %> <p>
  </body>
</html>

纯文本版

app/views/comment_mailer/comment_notify_email.text.erb
There is a new comment on your blog

<%= @comment.content %>

url: <%= @url %>

在Controller 中发送Email

app/controllers/comments_controller.rb
class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.new(params[:comment])
    if @comment.save
      CommentMailer.comment_notify_email(@comment).deliver
      redirect_to @post
    end
  end
end

配置

config/environments/development.rb
config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address              => "smtp.gmail.com",
    :port                 => 587,
    :user_name            => 'poshboytl',
    :password             =>  ENV['GMAIL_PASS'],
    :authentication       => 'plain',
    :enable_starttls_auto => true
  }
Similar Episodes