-
Notifications
You must be signed in to change notification settings - Fork 0
/
rails_mailers_notes.txt
312 lines (216 loc) · 8.67 KB
/
rails_mailers_notes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
Action Mailer
Basics
=============================================================================
- Create
bin/rails generate mailer User
app/mailers/user_mailer.rb # User Mailer
app/mailers/application_mailer.rb # Main mailer
app/views/user_mailer # email content folder
app/views/layouts/mailer.text.erb # text email layout
app/views/layouts/mailer.html.erb # html email layout
test/mailers/user_mailer_test.rb
test/mailers/previews/user_mailer_preview.rb
--
Mailers:
class ApplicationMailer < ActionMailer::Base
default from: "[email protected]"
layout "mailer"
end
class UserMailer < ApplicationMailer
default from: '[email protected]'
def welcome_email
@user = params[:user]
@url = 'http://example.com/login'
mail(to: @user.email, subject: 'Welcome to My Awesome Site')
end
end
- multiple recepients
default to: -> { Admin.pluck(:email) }, from: '[email protected]'
- with name
default from: email_address_with_name('[email protected]', 'Example Company Notifications')
Or
mail(to: email_address_with_name(@user.email, @user.name), subject: 'Welcome to My Awesome Site')
- attachment
class ApplicationMailer < ActionMailer::Base
def welcome(recipient)
attachments['free_book.pdf'] = File.read('path/to/file.pdf')
mail(:to => recipient, :subject => "New account information")
end
end
- custom mimetype
encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
attachments['filename.jpg'] = {:mime_type => 'application/gzip', :encoding => 'SpecialEncoding', :content => encoded_content }
mail(:to => recipient, :subject => "New account information")
- inline attachment
attachments.inline['image.jpg'] = File.read('/path/to/image.jpg') --> in view: <%= image_tag attachments['image.jpg'].url %>
View:
class UserMailer < ApplicationMailer
def welcome_email ...
--> app/view/user_mailer/welcome_email.html.erb
Welcome to example.com, <%= @user.name %>
===============================================
You have successfully signed up to example.com,
your username is: <%= @user.login %>.
To login to the site, just follow this link: <%= @url %>.
Thanks for joining and have a great day!
- specify template
mail(to: @user.email, subject: 'Welcome to My Awesome Site', template_path: 'notifications', template_name: 'another') --> app/views/notifications/another.html.erb
- format
mail(to: @user.email, subject: 'Welcome to My Awesome Site') do |format|
format.html { render 'another_template' }
format.text { render plain: 'Render text' }
end
- Caching
config.action_mailer.perform_caching = true
<% cache do %>
<%= @company.name %>
<% end %>
- Layouts
class UserMailer < ApplicationMailer
layout 'awesome' # use awesome.(html|text).erb as the layout
end
format.html { render layout: 'my_layout' }
- Call:
UserMailer.with(user: @user).welcome_email.deliver_later --> queue
- If you want to use cronjob use deliver_now
class SendWeeklySummary
def run
User.find_each do |user|
UserMailer.with(user: user).weekly_summary.deliver_now
end
end
end
- Previews
- previews are located under: test/mailers/previews/user_mailer_preview.rb
class UserMailerPreview < ActionMailer::Preview
def welcome_email
UserMailer.with(user: User.first).welcome_email
end
end
- if you have rspec installed, it will use: spec/mailers/previews/user_mailer_preview.rb
- to disable it an use default: application.rb
config.action_mailer.preview_path = "#{Rails.root}/test/mailers/previews"
* Remember, if you have two versions of emails (text, html)
mail(to: @user.email, subject: 'Welcome to My Awesome Site') do |format|
format.html
format.text
end
- and make use you have both: welcome_email.html.erb welcome_email.text.erb
- in the preview you will get select box to choose ..
- to send the email as text, remove the option format.html
- you can use conditions as: format.html if something?
- Callbacks
before_action :set_inviter_and_invitee
before_action { @account = params[:inviter].account }
default to: -> { @invitee.email_address },
from: -> { common_address(@inviter) },
reply_to: -> { @inviter.email_address_with_name }
private
def set_inviter_and_invitee
@inviter = params[:inviter]
@invitee = params[:invitee]
end
- Using an after_action callback also enables you to override delivery method settings by updating mail.delivery_method.settings.
after_action :set_delivery_options,
:prevent_delivery_to_guests,
:set_business_headers
private
def set_delivery_options
# You have access to the mail instance,
# @business and @user instance variables here
if @business && @business.has_smtp_settings?
mail.delivery_method.settings.merge!(@business.smtp_settings)
end
end
def prevent_delivery_to_guests
if @user && @user.guest?
mail.perform_deliveries = false
end
end
def set_business_headers
if @business
headers["X-SMTPAPI-CATEGORY"] = @business.code
end
end
- Configuration
config.action_mailer.default_url_options = { host: 'example.com' } # will be used to configure generated urls
<%= link_to 'welcome', welcome_url %> # you can't use welcome_path
<%= url_for(host: 'example.com', controller: 'welcome', action: 'greeting') %>
<%= user_url(@user, host: 'example.com') %>
config.asset_host = 'http://example.com' # to use assets as
<%= image_tag 'image.jpg' %>
- Delivery options can be dynamic
def welcome_email
delivery_options = { user_name: params[:company].smtp_user,
password: params[:company].smtp_password,
address: params[:company].smtp_host }
mail(to: @user.email,
subject: "Please see the Terms and Conditions attached",
delivery_method_options: delivery_options)
- no rendering, you can send body
def welcome_email
mail(to: params[:user].email,
body: params[:email_body],
content_type: "text/html",
subject: "Already rendered!")
- SENDMAIL
config.action_mailer.delivery_method = :sendmail
# Defaults to:
# config.action_mailer.sendmail_settings = {
# location: '/usr/sbin/sendmail',
# arguments: '-i'
# }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_options = {from: '[email protected]'}
- GMAIL
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'example.com',
user_name: '<username>',
password: '<password>',
authentication: 'plain',
enable_starttls_auto: true,
open_timeout: 5,
read_timeout: 5 }
- Intercepting Emails
- Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to register classes that are called during the mail delivery life cycle of every email sent.
- Interceptors allow you to make modifications to emails before they are handed off to the delivery agents.
- An interceptor class must implement the ::delivering_email(message) method which will be called before the email is sent.
class SandboxEmailInterceptor
def self.delivering_email(message)
message.to = ['[email protected]']
end
end
- Before the interceptor can do its job you need to register it using the interceptors config option.
- You can do this in an initializer file like config/initializers/mail_interceptors.rb:
Rails.application.configure do
if Rails.env.staging?
config.action_mailer.interceptors = %w[SandboxEmailInterceptor]
end
end
- Observing Emails
- Observers give you access to the email message after it has been sent.
- An observer class must implement the :delivered_email(message) method, which will be called after the email is sent.
class EmailDeliveryObserver
def self.delivered_email(message)
EmailDelivery.log(message)
end
end
- Similar to interceptors, you must register observers using the observers config option.
- You can do this in an initializer file like config/initializers/mail_observers.rb:
Rails.application.configure do
config.action_mailer.observers = %w[EmailDeliveryObserver]
end
- Using athird party tool
# https://mailcatcher.me/
> gem install mailcatcher
> mailcatcher
- Go to http://127.0.0.1:1080/
- Send mail through smtp://127.0.0.1:1025
- Config
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { :address => '127.0.0.1', :port => 1025 }
config.action_mailer.raise_delivery_errors = false