1 import { createTransport, Transporter } from 'nodemailer'
2 import { isTestInstance } from '../helpers/core-utils'
3 import { bunyanLogger, logger } from '../helpers/logger'
4 import { CONFIG, isEmailEnabled } from '../initializers/config'
5 import { JobQueue } from './job-queue'
6 import { EmailPayload } from './job-queue/handlers/email'
7 import { readFileSync } from 'fs-extra'
8 import { WEBSERVER } from '../initializers/constants'
14 MVideoBlacklistLightVideo,
16 } from '../typings/models/video'
17 import { MActorFollowActors, MActorFollowFull, MUser } from '../typings/models'
18 import { MVideoImport, MVideoImportVideo } from '@server/typings/models/video/video-import'
20 type SendEmailOptions = {
25 fromDisplayName?: string
31 private static instance: Emailer
32 private initialized = false
33 private transporter: Transporter
35 private constructor () {
39 // Already initialized
40 if (this.initialized === true) return
41 this.initialized = true
43 if (isEmailEnabled()) {
44 if (CONFIG.SMTP.TRANSPORT === 'smtp') {
45 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
48 if (CONFIG.SMTP.CA_FILE) {
50 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
55 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
57 user: CONFIG.SMTP.USERNAME,
58 pass: CONFIG.SMTP.PASSWORD
62 this.transporter = createTransport({
63 host: CONFIG.SMTP.HOSTNAME,
64 port: CONFIG.SMTP.PORT,
65 secure: CONFIG.SMTP.TLS,
66 debug: CONFIG.LOG.LEVEL === 'debug',
67 logger: bunyanLogger as any,
68 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
73 logger.info('Using sendmail to send emails')
75 this.transporter = createTransport({
78 path: CONFIG.SMTP.SENDMAIL
82 if (!isTestInstance()) {
83 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
89 if (CONFIG.SMTP.TRANSPORT === 'sendmail') {
90 return !!CONFIG.SMTP.SENDMAIL
91 } else if (CONFIG.SMTP.TRANSPORT === 'smtp') {
92 return !!CONFIG.SMTP.HOSTNAME && !!CONFIG.SMTP.PORT
98 async checkConnectionOrDie () {
99 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
101 logger.info('Testing SMTP server...')
104 const success = await this.transporter.verify()
105 if (success !== true) this.dieOnConnectionFailure()
107 logger.info('Successfully connected to SMTP server.')
109 this.dieOnConnectionFailure(err)
113 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
114 const channelName = video.VideoChannel.getDisplayName()
115 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
117 const text = 'Hi dear user,\n\n' +
118 `Your subscription ${channelName} just published a new video: ${video.name}` +
120 `You can view it on ${videoUrl} ` +
123 `${CONFIG.EMAIL.BODY.SIGNATURE}`
125 const emailPayload: EmailPayload = {
127 subject: CONFIG.EMAIL.SUBJECT.PREFIX + channelName + ' just published a new video',
131 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
134 addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
135 const followerName = actorFollow.ActorFollower.Account.getDisplayName()
136 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
138 const text = 'Hi dear user,\n\n' +
139 `Your ${followType} ${followingName} has a new subscriber: ${followerName}` +
142 `${CONFIG.EMAIL.BODY.SIGNATURE}`
144 const emailPayload: EmailPayload = {
146 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New follower on your channel ' + followingName,
150 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
153 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
154 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
156 const text = 'Hi dear admin,\n\n' +
157 `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}` +
160 `${CONFIG.EMAIL.BODY.SIGNATURE}`
162 const emailPayload: EmailPayload = {
164 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New instance follower',
168 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
171 addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) {
172 const text = 'Hi dear admin,\n\n' +
173 `Your instance automatically followed a new instance: ${actorFollow.ActorFollowing.url}` +
176 `${CONFIG.EMAIL.BODY.SIGNATURE}`
178 const emailPayload: EmailPayload = {
180 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Auto instance following',
184 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
187 myVideoPublishedNotification (to: string[], video: MVideo) {
188 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
190 const text = 'Hi dear user,\n\n' +
191 `Your video ${video.name} has been published.` +
193 `You can view it on ${videoUrl} ` +
196 `${CONFIG.EMAIL.BODY.SIGNATURE}`
198 const emailPayload: EmailPayload = {
200 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Your video ${video.name} is published`,
204 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
207 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
208 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
210 const text = 'Hi dear user,\n\n' +
211 `Your video import ${videoImport.getTargetIdentifier()} is finished.` +
213 `You can view the imported video on ${videoUrl} ` +
216 `${CONFIG.EMAIL.BODY.SIGNATURE}`
218 const emailPayload: EmailPayload = {
220 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Your video import ${videoImport.getTargetIdentifier()} is finished`,
224 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
227 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
228 const importUrl = WEBSERVER.URL + '/my-account/video-imports'
230 const text = 'Hi dear user,\n\n' +
231 `Your video import ${videoImport.getTargetIdentifier()} encountered an error.` +
233 `See your videos import dashboard for more information: ${importUrl}` +
236 `${CONFIG.EMAIL.BODY.SIGNATURE}`
238 const emailPayload: EmailPayload = {
240 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Your video import ${videoImport.getTargetIdentifier()} encountered an error`,
244 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
247 addNewCommentOnMyVideoNotification (to: string[], comment: MCommentOwnerVideo) {
248 const accountName = comment.Account.getDisplayName()
249 const video = comment.Video
250 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
252 const text = 'Hi dear user,\n\n' +
253 `A new comment has been posted by ${accountName} on your video ${video.name}` +
255 `You can view it on ${commentUrl} ` +
258 `${CONFIG.EMAIL.BODY.SIGNATURE}`
260 const emailPayload: EmailPayload = {
262 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New comment on your video ' + video.name,
266 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
269 addNewCommentMentionNotification (to: string[], comment: MCommentOwnerVideo) {
270 const accountName = comment.Account.getDisplayName()
271 const video = comment.Video
272 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
274 const text = 'Hi dear user,\n\n' +
275 `${accountName} mentioned you on video ${video.name}` +
277 `You can view the comment on ${commentUrl} ` +
280 `${CONFIG.EMAIL.BODY.SIGNATURE}`
282 const emailPayload: EmailPayload = {
284 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Mention on video ' + video.name,
288 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
291 addVideoAbuseModeratorsNotification (to: string[], videoAbuse: MVideoAbuseVideo) {
292 const videoUrl = WEBSERVER.URL + videoAbuse.Video.getWatchStaticPath()
294 const text = 'Hi,\n\n' +
295 `${WEBSERVER.HOST} received an abuse for the following video: ${videoUrl}\n\n` +
297 `${CONFIG.EMAIL.BODY.SIGNATURE}`
299 const emailPayload: EmailPayload = {
301 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Received a video abuse',
305 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
308 addVideoAutoBlacklistModeratorsNotification (to: string[], videoBlacklist: MVideoBlacklistLightVideo) {
309 const VIDEO_AUTO_BLACKLIST_URL = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
310 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
312 const text = 'Hi,\n\n' +
313 'A recently added video was auto-blacklisted and requires moderator review before publishing.' +
315 `You can view it and take appropriate action on ${videoUrl}` +
317 `A full list of auto-blacklisted videos can be reviewed here: ${VIDEO_AUTO_BLACKLIST_URL}` +
320 `${CONFIG.EMAIL.BODY.SIGNATURE}`
322 const emailPayload: EmailPayload = {
324 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'An auto-blacklisted video is awaiting review',
328 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
331 addNewUserRegistrationNotification (to: string[], user: MUser) {
332 const text = 'Hi,\n\n' +
333 `User ${user.username} just registered on ${WEBSERVER.HOST} PeerTube instance.\n\n` +
335 `${CONFIG.EMAIL.BODY.SIGNATURE}`
337 const emailPayload: EmailPayload = {
339 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New user registration on ' + WEBSERVER.HOST,
343 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
346 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
347 const videoName = videoBlacklist.Video.name
348 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
350 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
351 const blockedString = `Your video ${videoName} (${videoUrl} on ${WEBSERVER.HOST} has been blacklisted${reasonString}.`
353 const text = 'Hi,\n\n' +
357 `${CONFIG.EMAIL.BODY.SIGNATURE}`
359 const emailPayload: EmailPayload = {
361 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Video ${videoName} blacklisted`,
365 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
368 addVideoUnblacklistNotification (to: string[], video: MVideo) {
369 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
371 const text = 'Hi,\n\n' +
372 `Your video ${video.name} (${videoUrl}) on ${WEBSERVER.HOST} has been unblacklisted.` +
375 `${CONFIG.EMAIL.BODY.SIGNATURE}`
377 const emailPayload: EmailPayload = {
379 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Video ${video.name} unblacklisted`,
383 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
386 addPasswordResetEmailJob (to: string, resetPasswordUrl: string) {
387 const text = 'Hi dear user,\n\n' +
388 `A reset password procedure for your account ${to} has been requested on ${WEBSERVER.HOST} ` +
389 `Please follow this link to reset it: ${resetPasswordUrl} (the link will expire within 1 hour)\n\n` +
390 'If you are not the person who initiated this request, please ignore this email.\n\n' +
392 `${CONFIG.EMAIL.BODY.SIGNATURE}`
394 const emailPayload: EmailPayload = {
396 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Reset your password',
400 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
403 addPasswordCreateEmailJob (username: string, to: string, resetPasswordUrl: string) {
404 const text = 'Hi,\n\n' +
405 `Welcome to your ${WEBSERVER.HOST} PeerTube instance. Your username is: ${username}.\n\n` +
406 `Please set your password by following this link: ${resetPasswordUrl} (this link will expire within seven days).\n\n` +
408 `${CONFIG.EMAIL.BODY.SIGNATURE}`
410 const emailPayload: EmailPayload = {
412 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New PeerTube account password',
416 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
419 addVerifyEmailJob (to: string, verifyEmailUrl: string) {
420 const text = 'Welcome to PeerTube,\n\n' +
421 `To start using PeerTube on ${WEBSERVER.HOST} you must verify your email! ` +
422 `Please follow this link to verify this email belongs to you: ${verifyEmailUrl}\n\n` +
423 'If you are not the person who initiated this request, please ignore this email.\n\n' +
425 `${CONFIG.EMAIL.BODY.SIGNATURE}`
427 const emailPayload: EmailPayload = {
429 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Verify your email',
433 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
436 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
437 const reasonString = reason ? ` for the following reason: ${reason}` : ''
438 const blockedWord = blocked ? 'blocked' : 'unblocked'
439 const blockedString = `Your account ${user.username} on ${WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
441 const text = 'Hi,\n\n' +
445 `${CONFIG.EMAIL.BODY.SIGNATURE}`
447 const to = user.email
448 const emailPayload: EmailPayload = {
450 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Account ' + blockedWord,
454 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
457 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
458 const text = 'Hello dear admin,\n\n' +
459 fromName + ' sent you a message' +
460 '\n\n---------------------------------------\n\n' +
462 '\n\n---------------------------------------\n\n' +
466 const emailPayload: EmailPayload = {
467 fromDisplayName: fromEmail,
469 to: [ CONFIG.ADMIN.EMAIL ],
470 subject: CONFIG.EMAIL.SUBJECT.PREFIX + subject,
474 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
477 async sendMail (options: EmailPayload) {
478 if (!isEmailEnabled()) {
479 throw new Error('Cannot send mail because SMTP is not configured.')
482 const fromDisplayName = options.fromDisplayName
483 ? options.fromDisplayName
486 for (const to of options.to) {
487 await this.transporter.sendMail({
488 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`,
489 replyTo: options.replyTo,
491 subject: options.subject,
497 private dieOnConnectionFailure (err?: Error) {
498 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
502 static get Instance () {
503 return this.instance || (this.instance = new this())
507 // ---------------------------------------------------------------------------