forked from lookback/meteor-emails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
emails.coffee
400 lines (325 loc) · 12 KB
/
emails.coffee
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# `lookback:emails` is a small package for Meteor which helps you
# tremendously in the process of building, testing and debugging
# HTML emails in Meteor applications.
#
# See the [GitHub repo](https://github.com/lookback/meteor-emails) for README.
# Made by Johan Brook for [Lookback](https://github.com/lookback).
TAG = 'mailer'
# ## Setup
# Main exported symbol with some initial settings:
#
# - `routePrefix` is the top level path for the preview and send routes (see further down).
# - `baseUrl` is what root domain to base relative paths from.
# - `testEmail`, when testing emails, set this variable.
# - `logger`, optionally inject an external logger. Defaults to `console`.
# - `disabled`, optionally disable the actual email sending. Useful for E2E testing. Defaults to `false`.
# - `addRoutes`, should we add preview and send routes? Defaults to `true` in development.
Mailer =
settings:
silent: false
routePrefix: 'emails'
baseUrl: process.env.ROOT_URL
testEmail: null
logger: console
disabled: false
addRoutes: process.env.NODE_ENV is 'development'
language: 'html'
plainText: true
plainTextOpts: {}
juiceOpts:
preserveMediaQueries: true
removeStyleTags: true
webResources:
images: false
config: (newSettings) ->
@settings = _.extend(@settings, newSettings)
# ## Deps
#
Utils = share.MailerUtils
# ## Template helpers
#
# Built-in template helpers.
Helpers =
# `baseUrl` gives you a full absolute URL from a relative path.
#
# {{ baseUrl '/some-path' }} => http://root-domain.com/some-path
baseUrl: (path) ->
Utils.joinUrl(Mailer.settings.baseUrl, path)
# `emailUrlFor` takes an Iron Router route (with optional params) and
# creates an absolute URL.
#
# {{ emailUrlFor 'myRoute' param='foo' }} => http://root-domain.com/my-route/foo
emailUrlFor: (routeName, params) ->
# if Iron Router
if Router?
Utils.joinUrl Mailer.settings.baseUrl, Router.path.call(Router, routeName, params.hash)
# if Flow Router
if FlowRouter?
baseUrl = Utils.joinUrl Mailer.settings.baseUrl, FlowRouter.path.call(FlowRouter, routeName, params.hash)
# # The mailer
#
# This is the "blueprint" of the Mailer object. It has the following interface:
#
# - `precompile`
# - `render`
# - `send`
#
# As you can see, the mailer takes care of precompiling and rendering templates
# with data, as well as sending emails from those templates.
MailerClass = (options) ->
check options, Match.ObjectIncluding(
# Mailer *must* take a `templates` object with template names as keys.
templates: Object
# Take optional template helpers.
helpers: Match.Optional Object
# Take an optional layoute template object.
layout: Match.Optional Match.OneOf(Object, Boolean)
)
settings = _.extend({}, Mailer.settings, options.settings)
globalHelpers = _.extend({}, Helpers, Blaze._globalHelpers, options.helpers)
Utils.setupLogger(settings.logger, suppressInfo: settings.silent)
addHelpers = (template) ->
check template.name, String
check template.helpers, Match.Optional Object
# Use the built-in helpers, any global Blaze helpers, and injected helpers
# from options, and *additional* template helpers, and apply them to
# the template.
Template[template.name].helpers _.extend({}, globalHelpers, template.helpers)
# ## Compile
#
# Function for compiling a template with a name and path to
# a HTML file to a template function, to be placed
# in the Template namespace.
#
# A `template` must have a path to a template HTML file, and
# can optionally have paths to any SCSS and CSS stylesheets.
compile = (template) ->
check template, Match.ObjectIncluding(
path: String
name: String
scss: Match.Optional String
css: Match.Optional String
layout: Match.Optional Match.OneOf(Boolean,
name: String
path: String
scss: Match.Optional String
css: Match.Optional String
)
)
# Read the template as a string.
try
content = Utils.readFile template.path
catch ex
Utils.Logger.error 'Could not read template file: '+template.path, TAG
return false
layout = template.layout or options.layout
if layout and template.layout isnt false
layoutContent = Utils.readFile(layout.path)
SSR.compileTemplate(layout.name, layoutContent, language: settings.language)
addHelpers layout
# This will place the template function in
#
# Template.<template.name>
tmpl = SSR.compileTemplate(template.name, content, language: settings.language)
# Add helpers to template.
addHelpers template
return tmpl
# ## Render
#
# Render a template by name, with optional data context.
# Will compile the template if not done already.
render = (templateName, data) ->
check templateName, String
check data, Match.Optional Object
template = _.findWhere(options.templates, name: templateName)
if !templateName of Template
compile template
tmpl = Template[templateName]
if not tmpl
throw new Meteor.Error 500, 'Could not find template: '+templateName
rendered = SSR.render tmpl, data
layout = template.layout or options.layout
if layout and template.layout isnt false
# When applying to a layout, some info from the template
# (like the first preview lines) needs to be applied to the
# layout scope as well.
#
# Thus we fetch a `preview` helper from the template or
# `preview` prop in the data context to apply to the layout.
if tmpl.__helpers.has 'preview'
preview = tmpl.__helpers.get('preview')
else if data.preview
preview = data.preview
# The `extraCSS` property on a `template` is applied to
# the layout in `<style>` tags. Ideal for media queries.
if template.extraCSS
try
css = Utils.readFile template.extraCSS
catch ex
Utils.Logger.error 'Could not add extra CSS when rendering '+templateName+': '+ex.message, TAG
layoutData = _.extend({}, data,
body: rendered
css: css
preview: preview
)
rendered = SSR.render layout.name, layoutData
rendered = Utils.addStylesheets(template, rendered, settings.juiceOpts)
rendered = Utils.addStylesheets(layout, rendered, settings.juiceOpts)
else
rendered = Utils.addStylesheets(template, rendered, settings.juiceOpts)
rendered = Utils.addDoctype rendered
return rendered
# Short hand function for converting HTML to plain text with some options.
toText = (html) ->
Utils.toText(html, settings.plainTextOpts)
# ## Send
#
# The main sending-email function. Takes a set of usual email options,
# including the template name and optional data object.
sendEmail = (options) ->
check options,
to: String
subject: String
template: String
replyTo: Match.Optional String
from: Match.Optional String
data: Match.Optional Object
headers: Match.Optional Object
defaults =
from: settings.from
if settings.replyTo
defaults.replyTo = settings.replyTo
opts = _.extend {}, defaults, options
# Render HTML with optional data context.
try
opts.html = render options.template, options.data
# create plain-text version from html
if settings.plainText
opts.text = toText(opts.html)
catch ex
Utils.Logger.error 'Could not render email before sending: ' + ex.message, TAG
return false
# Send email, unless sending is disabled
try
unless settings.disabled
Email.send(opts)
return true
catch ex
Utils.Logger.error 'Could not send email: ' + ex.message, TAG
return false
# ## Routes
#
# This package supports browser routes, so you can **preview**
# and **send email designs** from the browser.
# This function adds the `preview` route from a `template` object.
# It will apply the returned data from a `data` function on the
# provided `route` prop from the template.
previewAction = (opts, template, params) ->
check opts,
type: Match.OneOf('html', 'text')
return (template, params) ->
try
data = template.route.data and template.route.data.call(this, params)
catch ex
msg = 'Exception in '+template.name+' data function: '+ex.message
Utils.Logger.error msg, TAG
@writeHead 500
return @end msg
# Compile, since we wanna refresh markup and CSS inlining.
compile template
Utils.Logger.info "Rendering #{template.name} as #{opts.type} ...", TAG
try
html = render template.name, data
content = if opts.type is 'html' then html else toText(html)
Utils.Logger.info "Rendering successful!", TAG
catch ex
msg = 'Could not preview email: ' + ex.message
Utils.Logger.error msg, TAG
content = msg
@writeHead 200, 'Content-Type': if opts.type is 'html' then 'text/html' else 'text/plain'
@end(content, 'utf8')
# This function adds the `send` route, for easy sending emails from
# the browser.
sendAction = (template, params) ->
# Who to send to? It depends: it primarly reads from the `?to`
# query param, and secondly from the `testEmail` prop in settings.
to = params.query.to or settings.testEmail
Utils.Logger.info "Sending #{template.name} ...", TAG
if to?
try
data = template.route.data and template.route.data.call(this, params)
catch ex
Utils.Logger.error 'Exception in '+template.name+' data function: '+ex.message, TAG
return
res = sendEmail(
to: to
data: data
template: template.name
subject: '[TEST] ' + template.name
)
if res is false
@response.writeHead 500
msg = 'Did not send test email, something went wrong. Check the logs.'
else
@writeHead 200
# If there's no `MAIL_URL` environment variable, Meteor cannot send
# the email and echoes it out to `STDOUT` instead.
reallySentEmail = !!process.env.MAIL_URL
msg = if reallySentEmail then "Sent test email to #{to}" else "Sent email to STDOUT"
@end(msg)
else
@writeHead 400
@end("No testEmail provided.")
# Adds all the routes from a template.
addRoutes = (template) ->
check template.name, String
check template.route.path, String
types =
preview: previewAction(type: 'html')
text: previewAction(type: 'text')
send: sendAction
_.each types, (action, type) ->
# Typically `/emails/preview/myEmailTemplate`.
# Do some formatting. The `path` should be the prefix, followed by
# the type (`preview` or `send`). So it could look like
#
# /emails/preview/sampleTemplate/:param
#
# Also capitalize the first character in the template name for
# the name of the route, so it will look like `previewSample` for a
# template named `sample`.
path = "/#{settings.routePrefix}/#{type}" + template.route.path
name = Utils.capitalizeFirstChar(template.name)
routeName = "#{type}#{name}"
Utils.Logger.info "Add route: [#{routeName}] at path " + path, TAG
# we use Picker for server side routes
Picker.route(path, (params, req, res) ->
action.call res, template, params
)
# ## Init
#
# Init routine. Precompiles all templates provided and
# setup routes if provided and if in dev mode.
init = ->
if options.templates
_.each options.templates, (template, name) ->
template.name = name
compile template
# Only add these routes when in dev mode or if forced.
if template.route and settings.addRoutes
addRoutes(template)
init()
# ## Export
#
# The "interface".
precompile: compile
render: render
send: sendEmail
# Exported symbol
#
# I wanna export a singleton symbol with an 'init'
# method, but still initialize variables in the main
# function body of 'MailerClass'.
Mailer.init = (opts) ->
mailer = MailerClass(opts)
_.extend(this, mailer)