]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/emailer.ts
Stricter email options typings
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
CommitLineData
d95d1559
C
1import { readFileSync } from 'fs-extra'
2import { merge } from 'lodash'
ecb4e35f 3import { createTransport, Transporter } from 'nodemailer'
d95d1559
C
4import { join } from 'path'
5import { VideoChannelModel } from '@server/models/video/video-channel'
6import { MVideoBlacklistLightVideo, MVideoBlacklistVideo } from '@server/types/models/video/video-blacklist'
7import { MVideoImport, MVideoImportVideo } from '@server/types/models/video/video-import'
9ff36c2d 8import { SANITIZE_OPTIONS, TEXT_WITH_HTML_RULES } from '@shared/core-utils'
594d3e48 9import { AbuseState, EmailPayload, UserAbuse } from '@shared/models'
cae2df6b 10import { SendEmailDefaultOptions } from '../../shared/models/server/emailer.model'
df4c603d 11import { isTestInstance, root } from '../helpers/core-utils'
05e67d62 12import { bunyanLogger, logger } from '../helpers/logger'
4c1c1709 13import { CONFIG, isEmailEnabled } from '../initializers/config'
6dd9de95 14import { WEBSERVER } from '../initializers/constants'
32a18cbf 15import { MAbuseFull, MAbuseMessage, MAccountDefault, MActorFollowActors, MActorFollowFull, MPlugin, MUser } from '../types/models'
d95d1559
C
16import { MCommentOwnerVideo, MVideo, MVideoAccountLight } from '../types/models/video'
17import { JobQueue } from './job-queue'
18
98b94643
K
19const sanitizeHtml = require('sanitize-html')
20const markdownItEmoji = require('markdown-it-emoji/light')
21const MarkdownItClass = require('markdown-it')
22const markdownIt = new MarkdownItClass('default', { linkify: true, breaks: true, html: true })
23
9ff36c2d 24markdownIt.enable(TEXT_WITH_HTML_RULES)
98b94643
K
25
26markdownIt.use(markdownItEmoji)
27
28const toSafeHtml = text => {
29 // Restore line feed
30 const textWithLineFeed = text.replace(/<br.?\/?>/g, '\r\n')
31
32 // Convert possible markdown (emojis, emphasis and lists) to html
33 const html = markdownIt.render(textWithLineFeed)
34
35 // Convert to safe Html
9ff36c2d 36 return sanitizeHtml(html, SANITIZE_OPTIONS)
98b94643
K
37}
38
df4c603d 39const Email = require('email-templates')
dee77e76 40
ecb4e35f
C
41class Emailer {
42
43 private static instance: Emailer
44 private initialized = false
45 private transporter: Transporter
46
a1587156
C
47 private constructor () {
48 }
ecb4e35f
C
49
50 init () {
51 // Already initialized
52 if (this.initialized === true) return
53 this.initialized = true
54
448487a6 55 if (!isEmailEnabled()) {
ecb4e35f
C
56 if (!isTestInstance()) {
57 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
58 }
ecb4e35f 59
448487a6 60 return
ed3f089c 61 }
448487a6
C
62
63 if (CONFIG.SMTP.TRANSPORT === 'smtp') this.initSMTPTransport()
64 else if (CONFIG.SMTP.TRANSPORT === 'sendmail') this.initSendmailTransport()
3b3b1820
C
65 }
66
75594f47 67 async checkConnection () {
ed3f089c 68 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
ecb4e35f 69
3d3441d6
C
70 logger.info('Testing SMTP server...')
71
ecb4e35f
C
72 try {
73 const success = await this.transporter.verify()
75594f47 74 if (success !== true) this.warnOnConnectionFailure()
ecb4e35f
C
75
76 logger.info('Successfully connected to SMTP server.')
77 } catch (err) {
75594f47 78 this.warnOnConnectionFailure(err)
ecb4e35f
C
79 }
80 }
81
453e83ea 82 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
cef534ed 83 const channelName = video.VideoChannel.getDisplayName()
6dd9de95 84 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
cef534ed 85
ecb4e35f 86 const emailPayload: EmailPayload = {
cef534ed 87 to,
df4c603d
RK
88 subject: channelName + ' just published a new video',
89 text: `Your subscription ${channelName} just published a new video: "${video.name}".`,
90 locals: {
91 title: 'New content ',
92 action: {
93 text: 'View video',
94 url: videoUrl
95 }
96 }
ecb4e35f
C
97 }
98
99 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
100 }
101
8424c402 102 addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
f7cc67b4
C
103 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
104
f7cc67b4 105 const emailPayload: EmailPayload = {
df4c603d 106 template: 'follower-on-channel',
f7cc67b4 107 to,
df4c603d
RK
108 subject: `New follower on your channel ${followingName}`,
109 locals: {
110 followerName: actorFollow.ActorFollower.Account.getDisplayName(),
111 followerUrl: actorFollow.ActorFollower.url,
112 followingName,
113 followingUrl: actorFollow.ActorFollowing.url,
114 followType
115 }
f7cc67b4
C
116 }
117
118 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
119 }
120
453e83ea 121 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
883993c8
C
122 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
123
883993c8
C
124 const emailPayload: EmailPayload = {
125 to,
df4c603d
RK
126 subject: 'New instance follower',
127 text: `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}.`,
128 locals: {
129 title: 'New instance follower',
130 action: {
131 text: 'Review followers',
132 url: WEBSERVER.URL + '/admin/follows/followers-list'
133 }
134 }
883993c8
C
135 }
136
137 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
138 }
139
8424c402 140 addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) {
df4c603d 141 const instanceUrl = actorFollow.ActorFollowing.url
8424c402
C
142 const emailPayload: EmailPayload = {
143 to,
df4c603d
RK
144 subject: 'Auto instance following',
145 text: `Your instance automatically followed a new instance: <a href="${instanceUrl}">${instanceUrl}</a>.`
8424c402
C
146 }
147
148 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
149 }
150
453e83ea 151 myVideoPublishedNotification (to: string[], video: MVideo) {
6dd9de95 152 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
dc133480 153
dc133480
C
154 const emailPayload: EmailPayload = {
155 to,
df4c603d
RK
156 subject: `Your video ${video.name} has been published`,
157 text: `Your video "${video.name}" has been published.`,
158 locals: {
159 title: 'You video is live',
160 action: {
161 text: 'View video',
162 url: videoUrl
163 }
164 }
dc133480
C
165 }
166
167 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
168 }
169
453e83ea 170 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
6dd9de95 171 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
dc133480 172
dc133480
C
173 const emailPayload: EmailPayload = {
174 to,
df4c603d
RK
175 subject: `Your video import ${videoImport.getTargetIdentifier()} is complete`,
176 text: `Your video "${videoImport.getTargetIdentifier()}" just finished importing.`,
177 locals: {
178 title: 'Import complete',
179 action: {
180 text: 'View video',
181 url: videoUrl
182 }
183 }
dc133480
C
184 }
185
186 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
187 }
188
453e83ea 189 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
17119e4a 190 const importUrl = WEBSERVER.URL + '/my-library/video-imports'
dc133480 191
df4c603d
RK
192 const text =
193 `Your video import "${videoImport.getTargetIdentifier()}" encountered an error.` +
a1587156 194 '\n\n' +
df4c603d 195 `See your videos import dashboard for more information: <a href="${importUrl}">${importUrl}</a>.`
dc133480
C
196
197 const emailPayload: EmailPayload = {
198 to,
df4c603d
RK
199 subject: `Your video import "${videoImport.getTargetIdentifier()}" encountered an error`,
200 text,
201 locals: {
202 title: 'Import failed',
203 action: {
204 text: 'Review imports',
205 url: importUrl
206 }
207 }
dc133480
C
208 }
209
210 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
211 }
212
453e83ea 213 addNewCommentOnMyVideoNotification (to: string[], comment: MCommentOwnerVideo) {
cef534ed 214 const video = comment.Video
df4c603d 215 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
6dd9de95 216 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
98b94643 217 const commentHtml = toSafeHtml(comment.text)
cef534ed 218
d9eaee39 219 const emailPayload: EmailPayload = {
df4c603d 220 template: 'video-comment-new',
cef534ed 221 to,
df4c603d
RK
222 subject: 'New comment on your video ' + video.name,
223 locals: {
224 accountName: comment.Account.getDisplayName(),
225 accountUrl: comment.Account.Actor.url,
226 comment,
98b94643 227 commentHtml,
df4c603d
RK
228 video,
229 videoUrl,
230 action: {
231 text: 'View comment',
232 url: commentUrl
233 }
234 }
d9eaee39
JM
235 }
236
237 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
238 }
239
453e83ea 240 addNewCommentMentionNotification (to: string[], comment: MCommentOwnerVideo) {
f7cc67b4
C
241 const accountName = comment.Account.getDisplayName()
242 const video = comment.Video
df4c603d 243 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
6dd9de95 244 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
98b94643 245 const commentHtml = toSafeHtml(comment.text)
f7cc67b4 246
f7cc67b4 247 const emailPayload: EmailPayload = {
df4c603d 248 template: 'video-comment-mention',
f7cc67b4 249 to,
df4c603d
RK
250 subject: 'Mention on video ' + video.name,
251 locals: {
252 comment,
98b94643 253 commentHtml,
df4c603d
RK
254 video,
255 videoUrl,
256 accountName,
257 action: {
258 text: 'View comment',
259 url: commentUrl
260 }
261 }
f7cc67b4
C
262 }
263
264 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
265 }
266
d95d1559 267 addAbuseModeratorsNotification (to: string[], parameters: {
edbc9325 268 abuse: UserAbuse
d95d1559 269 abuseInstance: MAbuseFull
df4c603d
RK
270 reporter: string
271 }) {
d95d1559 272 const { abuse, abuseInstance, reporter } = parameters
ba75d268 273
d95d1559
C
274 const action = {
275 text: 'View report #' + abuse.id,
276 url: WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
277 }
278
279 let emailPayload: EmailPayload
280
281 if (abuseInstance.VideoAbuse) {
282 const video = abuseInstance.VideoAbuse.Video
283 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
284
285 emailPayload = {
286 template: 'video-abuse-new',
287 to,
288 subject: `New video abuse report from ${reporter}`,
289 locals: {
290 videoUrl,
291 isLocal: video.remote === false,
292 videoCreatedAt: new Date(video.createdAt).toLocaleString(),
293 videoPublishedAt: new Date(video.publishedAt).toLocaleString(),
294 videoName: video.name,
295 reason: abuse.reason,
cfde28ba
C
296 videoChannel: abuse.video.channel,
297 reporter,
d95d1559
C
298 action
299 }
300 }
301 } else if (abuseInstance.VideoCommentAbuse) {
302 const comment = abuseInstance.VideoCommentAbuse.VideoComment
303 const commentUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath() + ';threadId=' + comment.getThreadId()
304
305 emailPayload = {
4f32032f 306 template: 'video-comment-abuse-new',
d95d1559
C
307 to,
308 subject: `New comment abuse report from ${reporter}`,
309 locals: {
310 commentUrl,
310b5219 311 videoName: comment.Video.name,
d95d1559
C
312 isLocal: comment.isOwned(),
313 commentCreatedAt: new Date(comment.createdAt).toLocaleString(),
314 reason: abuse.reason,
315 flaggedAccount: abuseInstance.FlaggedAccount.getDisplayName(),
cfde28ba 316 reporter,
d95d1559
C
317 action
318 }
319 }
320 } else {
321 const account = abuseInstance.FlaggedAccount
322 const accountUrl = account.getClientUrl()
323
324 emailPayload = {
325 template: 'account-abuse-new',
326 to,
327 subject: `New account abuse report from ${reporter}`,
328 locals: {
329 accountUrl,
330 accountDisplayName: account.getDisplayName(),
331 isLocal: account.isOwned(),
332 reason: abuse.reason,
cfde28ba 333 reporter,
d95d1559 334 action
df4c603d
RK
335 }
336 }
ba75d268
C
337 }
338
339 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
340 }
341
594d3e48
C
342 addAbuseStateChangeNotification (to: string[], abuse: MAbuseFull) {
343 const text = abuse.state === AbuseState.ACCEPTED
344 ? 'Report #' + abuse.id + ' has been accepted'
345 : 'Report #' + abuse.id + ' has been rejected'
346
d573926e
C
347 const abuseUrl = WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
348
594d3e48
C
349 const action = {
350 text,
d573926e 351 url: abuseUrl
594d3e48
C
352 }
353
354 const emailPayload: EmailPayload = {
355 template: 'abuse-state-change',
356 to,
357 subject: text,
358 locals: {
359 action,
360 abuseId: abuse.id,
d573926e 361 abuseUrl,
594d3e48
C
362 isAccepted: abuse.state === AbuseState.ACCEPTED
363 }
364 }
365
366 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
367 }
368
d573926e
C
369 addAbuseNewMessageNotification (
370 to: string[],
371 options: {
372 target: 'moderator' | 'reporter'
373 abuse: MAbuseFull
374 message: MAbuseMessage
375 accountMessage: MAccountDefault
376 }) {
377 const { abuse, target, message, accountMessage } = options
378
379 const text = 'New message on report #' + abuse.id
380 const abuseUrl = target === 'moderator'
381 ? WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
382 : WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
594d3e48 383
594d3e48
C
384 const action = {
385 text,
d573926e 386 url: abuseUrl
594d3e48
C
387 }
388
389 const emailPayload: EmailPayload = {
390 template: 'abuse-new-message',
391 to,
392 subject: text,
393 locals: {
d573926e 394 abuseId: abuse.id,
594d3e48 395 abuseUrl: action.url,
d573926e 396 messageAccountName: accountMessage.getDisplayName(),
594d3e48
C
397 messageText: message.message,
398 action
399 }
400 }
401
402 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
403 }
404
df4c603d 405 async addVideoAutoBlacklistModeratorsNotification (to: string[], videoBlacklist: MVideoBlacklistLightVideo) {
32a18cbf 406 const videoAutoBlacklistUrl = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
8424c402 407 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
df4c603d 408 const channel = (await VideoChannelModel.loadByIdAndPopulateAccount(videoBlacklist.Video.channelId)).toFormattedSummaryJSON()
7ccddd7b
JM
409
410 const emailPayload: EmailPayload = {
df4c603d 411 template: 'video-auto-blacklist-new',
7ccddd7b 412 to,
df4c603d
RK
413 subject: 'A new video is pending moderation',
414 locals: {
415 channel,
416 videoUrl,
417 videoName: videoBlacklist.Video.name,
418 action: {
419 text: 'Review autoblacklist',
32a18cbf 420 url: videoAutoBlacklistUrl
df4c603d
RK
421 }
422 }
7ccddd7b
JM
423 }
424
425 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
426 }
427
453e83ea 428 addNewUserRegistrationNotification (to: string[], user: MUser) {
f7cc67b4 429 const emailPayload: EmailPayload = {
df4c603d 430 template: 'user-registered',
f7cc67b4 431 to,
2e4b8ae4 432 subject: `a new user registered on ${CONFIG.INSTANCE.NAME}: ${user.username}`,
df4c603d
RK
433 locals: {
434 user
435 }
f7cc67b4
C
436 }
437
438 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
439 }
440
453e83ea 441 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
cef534ed 442 const videoName = videoBlacklist.Video.name
6dd9de95 443 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
26b7305a 444
cef534ed 445 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
2e4b8ae4 446 const blockedString = `Your video ${videoName} (${videoUrl} on ${CONFIG.INSTANCE.NAME} has been blacklisted${reasonString}.`
26b7305a 447
26b7305a 448 const emailPayload: EmailPayload = {
cef534ed 449 to,
df4c603d
RK
450 subject: `Video ${videoName} blacklisted`,
451 text: blockedString,
452 locals: {
453 title: 'Your video was blacklisted'
454 }
26b7305a
C
455 }
456
457 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
458 }
459
453e83ea 460 addVideoUnblacklistNotification (to: string[], video: MVideo) {
6dd9de95 461 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
26b7305a 462
26b7305a 463 const emailPayload: EmailPayload = {
cef534ed 464 to,
df4c603d 465 subject: `Video ${video.name} unblacklisted`,
2e4b8ae4 466 text: `Your video "${video.name}" (${videoUrl}) on ${CONFIG.INSTANCE.NAME} has been unblacklisted.`,
df4c603d
RK
467 locals: {
468 title: 'Your video was unblacklisted'
469 }
26b7305a
C
470 }
471
472 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
473 }
474
32a18cbf 475 addNewPeerTubeVersionNotification (to: string[], latestVersion: string) {
32a18cbf
C
476 const emailPayload: EmailPayload = {
477 to,
478 template: 'peertube-version-new',
cae2df6b 479 subject: `A new PeerTube version is available: ${latestVersion}`,
32a18cbf
C
480 locals: {
481 latestVersion
482 }
483 }
484
485 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
486 }
487
488 addNewPlugionVersionNotification (to: string[], plugin: MPlugin) {
489 const pluginUrl = WEBSERVER.URL + '/admin/plugins/list-installed?pluginType=' + plugin.type
490
32a18cbf
C
491 const emailPayload: EmailPayload = {
492 to,
493 template: 'plugin-version-new',
cae2df6b 494 subject: `A new plugin/theme version is available: ${plugin.name}@${plugin.latestVersion}`,
32a18cbf
C
495 locals: {
496 pluginName: plugin.name,
497 latestVersion: plugin.latestVersion,
498 pluginUrl
499 }
500 }
501
502 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
503 }
504
963023ab 505 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
cef534ed 506 const emailPayload: EmailPayload = {
df4c603d 507 template: 'password-reset',
cef534ed 508 to: [ to ],
df4c603d
RK
509 subject: 'Reset your account password',
510 locals: {
963023ab 511 username,
df4c603d
RK
512 resetPasswordUrl
513 }
cef534ed
C
514 }
515
516 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
517 }
518
df4c603d 519 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
45f1bd72 520 const emailPayload: EmailPayload = {
df4c603d 521 template: 'password-create',
45f1bd72 522 to: [ to ],
df4c603d
RK
523 subject: 'Create your account password',
524 locals: {
525 username,
526 createPasswordUrl
527 }
45f1bd72
JL
528 }
529
530 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
531 }
532
963023ab 533 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
cef534ed 534 const emailPayload: EmailPayload = {
df4c603d 535 template: 'verify-email',
cef534ed 536 to: [ to ],
2e4b8ae4 537 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
df4c603d 538 locals: {
963023ab 539 username,
df4c603d
RK
540 verifyEmailUrl
541 }
cef534ed
C
542 }
543
544 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
545 }
546
453e83ea 547 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
eacb25c4
C
548 const reasonString = reason ? ` for the following reason: ${reason}` : ''
549 const blockedWord = blocked ? 'blocked' : 'unblocked'
eacb25c4
C
550
551 const to = user.email
552 const emailPayload: EmailPayload = {
553 to: [ to ],
df4c603d 554 subject: 'Account ' + blockedWord,
2e4b8ae4 555 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
eacb25c4
C
556 }
557
558 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
559 }
560
4e9fa5b7 561 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
a4101923 562 const emailPayload: EmailPayload = {
df4c603d 563 template: 'contact-form',
a4101923 564 to: [ CONFIG.ADMIN.EMAIL ],
df4c603d
RK
565 replyTo: `"${fromName}" <${fromEmail}>`,
566 subject: `(contact form) ${subject}`,
567 locals: {
568 fromName,
569 fromEmail,
b9cf3fb6
C
570 body,
571
572 // There are not notification preferences for the contact form
573 hideNotificationPreferences: true
df4c603d 574 }
a4101923
C
575 }
576
577 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
578 }
579
47f6cb31 580 async sendMail (options: EmailPayload) {
4c1c1709 581 if (!isEmailEnabled()) {
ecb4e35f
C
582 throw new Error('Cannot send mail because SMTP is not configured.')
583 }
584
df4c603d
RK
585 const fromDisplayName = options.from
586 ? options.from
2e4b8ae4 587 : CONFIG.INSTANCE.NAME
4759fedc 588
df4c603d
RK
589 const email = new Email({
590 send: true,
591 message: {
592 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
593 },
594 transport: this.transporter,
595 views: {
03fc1928 596 root: join(root(), 'dist', 'server', 'lib', 'emails')
df4c603d
RK
597 },
598 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
599 })
600
47f6cb31 601 for (const to of options.to) {
cae2df6b
C
602 const baseOptions: SendEmailDefaultOptions = {
603 template: 'common',
604 message: {
605 to,
606 from: options.from,
607 subject: options.subject,
608 replyTo: options.replyTo
609 },
610 locals: { // default variables available in all templates
611 WEBSERVER,
612 EMAIL: CONFIG.EMAIL,
613 instanceName: CONFIG.INSTANCE.NAME,
614 text: options.text,
615 subject: options.subject
616 }
617 }
618
619 // overriden/new variables given for a specific template in the payload
620 const sendOptions = merge(baseOptions, options)
621
622 await email.send(sendOptions)
03fc1928
C
623 .then(res => logger.debug('Sent email.', { res }))
624 .catch(err => logger.error('Error in email sender.', { err }))
47f6cb31 625 }
ecb4e35f
C
626 }
627
75594f47 628 private warnOnConnectionFailure (err?: Error) {
d5b7d911 629 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
ecb4e35f
C
630 }
631
448487a6
C
632 private initSMTPTransport () {
633 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
634
635 let tls
636 if (CONFIG.SMTP.CA_FILE) {
637 tls = {
638 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
639 }
640 }
641
642 let auth
643 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
644 auth = {
645 user: CONFIG.SMTP.USERNAME,
646 pass: CONFIG.SMTP.PASSWORD
647 }
648 }
649
650 this.transporter = createTransport({
651 host: CONFIG.SMTP.HOSTNAME,
652 port: CONFIG.SMTP.PORT,
653 secure: CONFIG.SMTP.TLS,
654 debug: CONFIG.LOG.LEVEL === 'debug',
655 logger: bunyanLogger as any,
656 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
657 tls,
658 auth
659 })
660 }
661
662 private initSendmailTransport () {
663 logger.info('Using sendmail to send emails')
664
665 this.transporter = createTransport({
666 sendmail: true,
667 newline: 'unix',
668 path: CONFIG.SMTP.SENDMAIL
669 })
670 }
671
ecb4e35f
C
672 static get Instance () {
673 return this.instance || (this.instance = new this())
674 }
675}
676
677// ---------------------------------------------------------------------------
678
679export {
8dc8a34e 680 Emailer
ecb4e35f 681}