Basic Mailer
suggest changeThis example uses four different files:
- The User model
- The User mailer
- The html template for the email
- The plain-text template for the email
The user model calls approved on the mailer and passes the approved post. That call can come from a callback, a controller, and so on. Building the message does not send it; call deliver_later (or deliver_now) on the returned message. The mailer then renders the HTML or plain-text template from the post, for example its title. By default, the template name matches the mailer method, which is why both are named approved.
user_mailer.rb
class UserMailer < ActionMailer::Base
default from: "donotreply@example.com"
def approved(post)
@title = post.title
@user = post.user
mail(to: @user.email, subject: "Your Post was Approved!")
end
end
user.rb
def approved(post)
UserMailer.approved(post).deliver_later
end
approved.html.erb
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Post Approved</title>
</head>
<body>
<h2>Congrats <%= @user.name %>! Your post (#<%= @title %>) has been approved!</h2>
<p>We look forward to your future posts!</p>
</body>
</html>
approved.text.erb
Congrats <%= @user.name %>! Your post (#<%= @title %>) has been approved!
We look forward to your future posts!
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents