http://railscasts-china.com/episodes/how-to-send-emails-in-rails
介绍如何在 Rails 中发送 Email.
在 console 中创建 mailer
rails g mailer CommentMailer
Mailer 代码,
class CommentMailer < ActionMailer::Base
default from: "[email protected]"
def comment_notify_email(comment)
@comment = comment
@url = post_url(@comment.post, host: 'localhost')
mail to: '[email protected]', subject: 'There is a new comment on your blog'
end
end
Mail View
<!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>
纯文本版
There is a new comment on your blog
<%= @comment.content %>
url: <%= @url %>
在 Controller 中发送 Email
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.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
}