1 import { readFileSync } from 'fs-extra'
2 import { merge } from 'lodash'
3 import { createTransport, Transporter } from 'nodemailer'
4 import { join } from 'path'
5 import { VideoChannelModel } from '@server/models/video/video-channel'
6 import { MVideoBlacklistLightVideo, MVideoBlacklistVideo } from '@server/types/models/video/video-blacklist'
7 import { MVideoImport, MVideoImportVideo } from '@server/types/models/video/video-import'
8 import { AbuseState, EmailPayload, UserAbuse } from '@shared/models'
9 import { SendEmailDefaultOptions } from '../../shared/models/server/emailer.model'
10 import { isTestInstance, root } from '../helpers/core-utils'
11 import { bunyanLogger, logger } from '../helpers/logger'
12 import { CONFIG, isEmailEnabled } from '../initializers/config'
13 import { WEBSERVER } from '../initializers/constants'
14 import { MAbuseFull, MAbuseMessage, MAccountDefault, MActorFollowActors, MActorFollowFull, MPlugin, MUser } from '../types/models'
15 import { MCommentOwnerVideo, MVideo, MVideoAccountLight } from '../types/models/video'
16 import { JobQueue } from './job-queue'
17 import { toSafeHtml } from '../helpers/markdown'
19 const Email = require('email-templates')
23 private static instance: Emailer
24 private initialized = false
25 private transporter: Transporter
27 private constructor () {
31 // Already initialized
32 if (this.initialized === true) return
33 this.initialized = true
35 if (!isEmailEnabled()) {
36 if (!isTestInstance()) {
37 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
43 if (CONFIG.SMTP.TRANSPORT === 'smtp') this.initSMTPTransport()
44 else if (CONFIG.SMTP.TRANSPORT === 'sendmail') this.initSendmailTransport()
47 async checkConnection () {
48 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
50 logger.info('Testing SMTP server...')
53 const success = await this.transporter.verify()
54 if (success !== true) this.warnOnConnectionFailure()
56 logger.info('Successfully connected to SMTP server.')
58 this.warnOnConnectionFailure(err)
62 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
63 const channelName = video.VideoChannel.getDisplayName()
64 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
66 const emailPayload: EmailPayload = {
68 subject: channelName + ' just published a new video',
69 text: `Your subscription ${channelName} just published a new video: "${video.name}".`,
71 title: 'New content ',
79 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
82 addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
83 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
85 const emailPayload: EmailPayload = {
86 template: 'follower-on-channel',
88 subject: `New follower on your channel ${followingName}`,
90 followerName: actorFollow.ActorFollower.Account.getDisplayName(),
91 followerUrl: actorFollow.ActorFollower.url,
93 followingUrl: actorFollow.ActorFollowing.url,
98 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
101 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
102 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
104 const emailPayload: EmailPayload = {
106 subject: 'New instance follower',
107 text: `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}.`,
109 title: 'New instance follower',
111 text: 'Review followers',
112 url: WEBSERVER.URL + '/admin/follows/followers-list'
117 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
120 addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) {
121 const instanceUrl = actorFollow.ActorFollowing.url
122 const emailPayload: EmailPayload = {
124 subject: 'Auto instance following',
125 text: `Your instance automatically followed a new instance: <a href="${instanceUrl}">${instanceUrl}</a>.`
128 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
131 myVideoPublishedNotification (to: string[], video: MVideo) {
132 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
134 const emailPayload: EmailPayload = {
136 subject: `Your video ${video.name} has been published`,
137 text: `Your video "${video.name}" has been published.`,
139 title: 'You video is live',
147 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
150 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
151 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
153 const emailPayload: EmailPayload = {
155 subject: `Your video import ${videoImport.getTargetIdentifier()} is complete`,
156 text: `Your video "${videoImport.getTargetIdentifier()}" just finished importing.`,
158 title: 'Import complete',
166 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
169 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
170 const importUrl = WEBSERVER.URL + '/my-library/video-imports'
173 `Your video import "${videoImport.getTargetIdentifier()}" encountered an error.` +
175 `See your videos import dashboard for more information: <a href="${importUrl}">${importUrl}</a>.`
177 const emailPayload: EmailPayload = {
179 subject: `Your video import "${videoImport.getTargetIdentifier()}" encountered an error`,
182 title: 'Import failed',
184 text: 'Review imports',
190 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
193 addNewCommentOnMyVideoNotification (to: string[], comment: MCommentOwnerVideo) {
194 const video = comment.Video
195 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
196 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
197 const commentHtml = toSafeHtml(comment.text)
199 const emailPayload: EmailPayload = {
200 template: 'video-comment-new',
202 subject: 'New comment on your video ' + video.name,
204 accountName: comment.Account.getDisplayName(),
205 accountUrl: comment.Account.Actor.url,
211 text: 'View comment',
217 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
220 addNewCommentMentionNotification (to: string[], comment: MCommentOwnerVideo) {
221 const accountName = comment.Account.getDisplayName()
222 const video = comment.Video
223 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
224 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
225 const commentHtml = toSafeHtml(comment.text)
227 const emailPayload: EmailPayload = {
228 template: 'video-comment-mention',
230 subject: 'Mention on video ' + video.name,
238 text: 'View comment',
244 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
247 addAbuseModeratorsNotification (to: string[], parameters: {
249 abuseInstance: MAbuseFull
252 const { abuse, abuseInstance, reporter } = parameters
255 text: 'View report #' + abuse.id,
256 url: WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
259 let emailPayload: EmailPayload
261 if (abuseInstance.VideoAbuse) {
262 const video = abuseInstance.VideoAbuse.Video
263 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
266 template: 'video-abuse-new',
268 subject: `New video abuse report from ${reporter}`,
271 isLocal: video.remote === false,
272 videoCreatedAt: new Date(video.createdAt).toLocaleString(),
273 videoPublishedAt: new Date(video.publishedAt).toLocaleString(),
274 videoName: video.name,
275 reason: abuse.reason,
276 videoChannel: abuse.video.channel,
281 } else if (abuseInstance.VideoCommentAbuse) {
282 const comment = abuseInstance.VideoCommentAbuse.VideoComment
283 const commentUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath() + ';threadId=' + comment.getThreadId()
286 template: 'video-comment-abuse-new',
288 subject: `New comment abuse report from ${reporter}`,
291 videoName: comment.Video.name,
292 isLocal: comment.isOwned(),
293 commentCreatedAt: new Date(comment.createdAt).toLocaleString(),
294 reason: abuse.reason,
295 flaggedAccount: abuseInstance.FlaggedAccount.getDisplayName(),
301 const account = abuseInstance.FlaggedAccount
302 const accountUrl = account.getClientUrl()
305 template: 'account-abuse-new',
307 subject: `New account abuse report from ${reporter}`,
310 accountDisplayName: account.getDisplayName(),
311 isLocal: account.isOwned(),
312 reason: abuse.reason,
319 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
322 addAbuseStateChangeNotification (to: string[], abuse: MAbuseFull) {
323 const text = abuse.state === AbuseState.ACCEPTED
324 ? 'Report #' + abuse.id + ' has been accepted'
325 : 'Report #' + abuse.id + ' has been rejected'
327 const abuseUrl = WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
334 const emailPayload: EmailPayload = {
335 template: 'abuse-state-change',
342 isAccepted: abuse.state === AbuseState.ACCEPTED
346 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
349 addAbuseNewMessageNotification (
352 target: 'moderator' | 'reporter'
354 message: MAbuseMessage
355 accountMessage: MAccountDefault
357 const { abuse, target, message, accountMessage } = options
359 const text = 'New message on report #' + abuse.id
360 const abuseUrl = target === 'moderator'
361 ? WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
362 : WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
369 const emailPayload: EmailPayload = {
370 template: 'abuse-new-message',
375 abuseUrl: action.url,
376 messageAccountName: accountMessage.getDisplayName(),
377 messageText: message.message,
382 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
385 async addVideoAutoBlacklistModeratorsNotification (to: string[], videoBlacklist: MVideoBlacklistLightVideo) {
386 const videoAutoBlacklistUrl = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
387 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
388 const channel = (await VideoChannelModel.loadAndPopulateAccount(videoBlacklist.Video.channelId)).toFormattedSummaryJSON()
390 const emailPayload: EmailPayload = {
391 template: 'video-auto-blacklist-new',
393 subject: 'A new video is pending moderation',
397 videoName: videoBlacklist.Video.name,
399 text: 'Review autoblacklist',
400 url: videoAutoBlacklistUrl
405 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
408 addNewUserRegistrationNotification (to: string[], user: MUser) {
409 const emailPayload: EmailPayload = {
410 template: 'user-registered',
412 subject: `a new user registered on ${CONFIG.INSTANCE.NAME}: ${user.username}`,
418 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
421 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
422 const videoName = videoBlacklist.Video.name
423 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
425 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
426 const blockedString = `Your video ${videoName} (${videoUrl} on ${CONFIG.INSTANCE.NAME} has been blacklisted${reasonString}.`
428 const emailPayload: EmailPayload = {
430 subject: `Video ${videoName} blacklisted`,
433 title: 'Your video was blacklisted'
437 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
440 addVideoUnblacklistNotification (to: string[], video: MVideo) {
441 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
443 const emailPayload: EmailPayload = {
445 subject: `Video ${video.name} unblacklisted`,
446 text: `Your video "${video.name}" (${videoUrl}) on ${CONFIG.INSTANCE.NAME} has been unblacklisted.`,
448 title: 'Your video was unblacklisted'
452 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
455 addNewPeerTubeVersionNotification (to: string[], latestVersion: string) {
456 const emailPayload: EmailPayload = {
458 template: 'peertube-version-new',
459 subject: `A new PeerTube version is available: ${latestVersion}`,
465 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
468 addNewPlugionVersionNotification (to: string[], plugin: MPlugin) {
469 const pluginUrl = WEBSERVER.URL + '/admin/plugins/list-installed?pluginType=' + plugin.type
471 const emailPayload: EmailPayload = {
473 template: 'plugin-version-new',
474 subject: `A new plugin/theme version is available: ${plugin.name}@${plugin.latestVersion}`,
476 pluginName: plugin.name,
477 latestVersion: plugin.latestVersion,
482 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
485 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
486 const emailPayload: EmailPayload = {
487 template: 'password-reset',
489 subject: 'Reset your account password',
496 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
499 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
500 const emailPayload: EmailPayload = {
501 template: 'password-create',
503 subject: 'Create your account password',
510 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
513 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
514 const emailPayload: EmailPayload = {
515 template: 'verify-email',
517 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
524 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
527 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
528 const reasonString = reason ? ` for the following reason: ${reason}` : ''
529 const blockedWord = blocked ? 'blocked' : 'unblocked'
531 const to = user.email
532 const emailPayload: EmailPayload = {
534 subject: 'Account ' + blockedWord,
535 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
538 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
541 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
542 const emailPayload: EmailPayload = {
543 template: 'contact-form',
544 to: [ CONFIG.ADMIN.EMAIL ],
545 replyTo: `"${fromName}" <${fromEmail}>`,
546 subject: `(contact form) ${subject}`,
552 // There are not notification preferences for the contact form
553 hideNotificationPreferences: true
557 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
560 async sendMail (options: EmailPayload) {
561 if (!isEmailEnabled()) {
562 throw new Error('Cannot send mail because SMTP is not configured.')
565 const fromDisplayName = options.from
567 : CONFIG.INSTANCE.NAME
569 const email = new Email({
572 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
574 transport: this.transporter,
576 root: join(root(), 'dist', 'server', 'lib', 'emails')
578 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
581 for (const to of options.to) {
582 const baseOptions: SendEmailDefaultOptions = {
587 subject: options.subject,
588 replyTo: options.replyTo
590 locals: { // default variables available in all templates
593 instanceName: CONFIG.INSTANCE.NAME,
595 subject: options.subject
599 // overriden/new variables given for a specific template in the payload
600 const sendOptions = merge(baseOptions, options)
602 await email.send(sendOptions)
603 .then(res => logger.debug('Sent email.', { res }))
604 .catch(err => logger.error('Error in email sender.', { err }))
608 private warnOnConnectionFailure (err?: Error) {
609 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
612 private initSMTPTransport () {
613 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
616 if (CONFIG.SMTP.CA_FILE) {
618 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
623 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
625 user: CONFIG.SMTP.USERNAME,
626 pass: CONFIG.SMTP.PASSWORD
630 this.transporter = createTransport({
631 host: CONFIG.SMTP.HOSTNAME,
632 port: CONFIG.SMTP.PORT,
633 secure: CONFIG.SMTP.TLS,
634 debug: CONFIG.LOG.LEVEL === 'debug',
635 logger: bunyanLogger as any,
636 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
642 private initSendmailTransport () {
643 logger.info('Using sendmail to send emails')
645 this.transporter = createTransport({
648 path: CONFIG.SMTP.SENDMAIL,
649 logger: bunyanLogger as any
653 static get Instance () {
654 return this.instance || (this.instance = new this())
658 // ---------------------------------------------------------------------------