1 import { createTransport, Transporter } from 'nodemailer'
2 import { isTestInstance } from '../helpers/core-utils'
3 import { bunyanLogger, logger } from '../helpers/logger'
4 import { CONFIG } from '../initializers'
5 import { UserModel } from '../models/account/user'
6 import { VideoModel } from '../models/video/video'
7 import { JobQueue } from './job-queue'
8 import { EmailPayload } from './job-queue/handlers/email'
9 import { readFileSync } from 'fs-extra'
10 import { VideoCommentModel } from '../models/video/video-comment'
11 import { VideoAbuseModel } from '../models/video/video-abuse'
12 import { VideoBlacklistModel } from '../models/video/video-blacklist'
13 import { VideoImportModel } from '../models/video/video-import'
14 import { ActorFollowModel } from '../models/activitypub/actor-follow'
16 type SendEmailOptions = {
21 fromDisplayName?: string
27 private static instance: Emailer
28 private initialized = false
29 private transporter: Transporter
31 private constructor () {}
34 // Already initialized
35 if (this.initialized === true) return
36 this.initialized = true
38 if (Emailer.isEnabled()) {
39 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
42 if (CONFIG.SMTP.CA_FILE) {
44 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
49 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
51 user: CONFIG.SMTP.USERNAME,
52 pass: CONFIG.SMTP.PASSWORD
56 this.transporter = createTransport({
57 host: CONFIG.SMTP.HOSTNAME,
58 port: CONFIG.SMTP.PORT,
59 secure: CONFIG.SMTP.TLS,
60 debug: CONFIG.LOG.LEVEL === 'debug',
61 logger: bunyanLogger as any,
62 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
67 if (!isTestInstance()) {
68 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
74 return !!CONFIG.SMTP.HOSTNAME && !!CONFIG.SMTP.PORT
77 async checkConnectionOrDie () {
78 if (!this.transporter) return
80 logger.info('Testing SMTP server...')
83 const success = await this.transporter.verify()
84 if (success !== true) this.dieOnConnectionFailure()
86 logger.info('Successfully connected to SMTP server.')
88 this.dieOnConnectionFailure(err)
92 addNewVideoFromSubscriberNotification (to: string[], video: VideoModel) {
93 const channelName = video.VideoChannel.getDisplayName()
94 const videoUrl = CONFIG.WEBSERVER.URL + video.getWatchStaticPath()
96 const text = `Hi dear user,\n\n` +
97 `Your subscription ${channelName} just published a new video: ${video.name}` +
99 `You can view it on ${videoUrl} ` +
104 const emailPayload: EmailPayload = {
106 subject: channelName + ' just published a new video',
110 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
113 addNewFollowNotification (to: string[], actorFollow: ActorFollowModel, followType: 'account' | 'channel') {
114 const followerName = actorFollow.ActorFollower.Account.getDisplayName()
115 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
117 const text = `Hi dear user,\n\n` +
118 `Your ${followType} ${followingName} has a new subscriber: ${followerName}` +
123 const emailPayload: EmailPayload = {
125 subject: 'New follower on your channel ' + followingName,
129 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
132 addNewInstanceFollowerNotification (to: string[], actorFollow: ActorFollowModel) {
133 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
135 const text = `Hi dear admin,\n\n` +
136 `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}` +
141 const emailPayload: EmailPayload = {
143 subject: 'New instance follower',
147 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
150 myVideoPublishedNotification (to: string[], video: VideoModel) {
151 const videoUrl = CONFIG.WEBSERVER.URL + video.getWatchStaticPath()
153 const text = `Hi dear user,\n\n` +
154 `Your video ${video.name} has been published.` +
156 `You can view it on ${videoUrl} ` +
161 const emailPayload: EmailPayload = {
163 subject: `Your video ${video.name} is published`,
167 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
170 myVideoImportSuccessNotification (to: string[], videoImport: VideoImportModel) {
171 const videoUrl = CONFIG.WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
173 const text = `Hi dear user,\n\n` +
174 `Your video import ${videoImport.getTargetIdentifier()} is finished.` +
176 `You can view the imported video on ${videoUrl} ` +
181 const emailPayload: EmailPayload = {
183 subject: `Your video import ${videoImport.getTargetIdentifier()} is finished`,
187 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
190 myVideoImportErrorNotification (to: string[], videoImport: VideoImportModel) {
191 const importUrl = CONFIG.WEBSERVER.URL + '/my-account/video-imports'
193 const text = `Hi dear user,\n\n` +
194 `Your video import ${videoImport.getTargetIdentifier()} encountered an error.` +
196 `See your videos import dashboard for more information: ${importUrl}` +
201 const emailPayload: EmailPayload = {
203 subject: `Your video import ${videoImport.getTargetIdentifier()} encountered an error`,
207 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
210 addNewCommentOnMyVideoNotification (to: string[], comment: VideoCommentModel) {
211 const accountName = comment.Account.getDisplayName()
212 const video = comment.Video
213 const commentUrl = CONFIG.WEBSERVER.URL + comment.getCommentStaticPath()
215 const text = `Hi dear user,\n\n` +
216 `A new comment has been posted by ${accountName} on your video ${video.name}` +
218 `You can view it on ${commentUrl} ` +
223 const emailPayload: EmailPayload = {
225 subject: 'New comment on your video ' + video.name,
229 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
232 addNewCommentMentionNotification (to: string[], comment: VideoCommentModel) {
233 const accountName = comment.Account.getDisplayName()
234 const video = comment.Video
235 const commentUrl = CONFIG.WEBSERVER.URL + comment.getCommentStaticPath()
237 const text = `Hi dear user,\n\n` +
238 `${accountName} mentioned you on video ${video.name}` +
240 `You can view the comment on ${commentUrl} ` +
245 const emailPayload: EmailPayload = {
247 subject: 'Mention on video ' + video.name,
251 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
254 addVideoAbuseModeratorsNotification (to: string[], videoAbuse: VideoAbuseModel) {
255 const videoUrl = CONFIG.WEBSERVER.URL + videoAbuse.Video.getWatchStaticPath()
257 const text = `Hi,\n\n` +
258 `${CONFIG.WEBSERVER.HOST} received an abuse for the following video ${videoUrl}\n\n` +
262 const emailPayload: EmailPayload = {
264 subject: '[PeerTube] Received a video abuse',
268 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
271 addVideoAutoBlacklistModeratorsNotification (to: string[], video: VideoModel) {
272 const VIDEO_AUTO_BLACKLIST_URL = CONFIG.WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
273 const videoUrl = CONFIG.WEBSERVER.URL + video.getWatchStaticPath()
275 const text = `Hi,\n\n` +
276 `A recently added video was auto-blacklisted and requires moderator review before publishing.` +
278 `You can view it and take appropriate action on ${videoUrl}` +
280 `A full list of auto-blacklisted videos can be reviewed here: ${VIDEO_AUTO_BLACKLIST_URL}` +
285 const emailPayload: EmailPayload = {
287 subject: '[PeerTube] An auto-blacklisted video is awaiting review',
291 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
294 addNewUserRegistrationNotification (to: string[], user: UserModel) {
295 const text = `Hi,\n\n` +
296 `User ${user.username} just registered on ${CONFIG.WEBSERVER.HOST} PeerTube instance.\n\n` +
300 const emailPayload: EmailPayload = {
302 subject: '[PeerTube] New user registration on ' + CONFIG.WEBSERVER.HOST,
306 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
309 addVideoBlacklistNotification (to: string[], videoBlacklist: VideoBlacklistModel) {
310 const videoName = videoBlacklist.Video.name
311 const videoUrl = CONFIG.WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
313 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
314 const blockedString = `Your video ${videoName} (${videoUrl} on ${CONFIG.WEBSERVER.HOST} has been blacklisted${reasonString}.`
316 const text = 'Hi,\n\n' +
322 const emailPayload: EmailPayload = {
324 subject: `[PeerTube] Video ${videoName} blacklisted`,
328 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
331 addVideoUnblacklistNotification (to: string[], video: VideoModel) {
332 const videoUrl = CONFIG.WEBSERVER.URL + video.getWatchStaticPath()
334 const text = 'Hi,\n\n' +
335 `Your video ${video.name} (${videoUrl}) on ${CONFIG.WEBSERVER.HOST} has been unblacklisted.` +
340 const emailPayload: EmailPayload = {
342 subject: `[PeerTube] Video ${video.name} unblacklisted`,
346 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
349 addPasswordResetEmailJob (to: string, resetPasswordUrl: string) {
350 const text = `Hi dear user,\n\n` +
351 `A reset password procedure for your account ${to} has been requested on ${CONFIG.WEBSERVER.HOST} ` +
352 `Please follow this link to reset it: ${resetPasswordUrl}\n\n` +
353 `If you are not the person who initiated this request, please ignore this email.\n\n` +
357 const emailPayload: EmailPayload = {
359 subject: 'Reset your PeerTube password',
363 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
366 addVerifyEmailJob (to: string, verifyEmailUrl: string) {
367 const text = `Welcome to PeerTube,\n\n` +
368 `To start using PeerTube on ${CONFIG.WEBSERVER.HOST} you must verify your email! ` +
369 `Please follow this link to verify this email belongs to you: ${verifyEmailUrl}\n\n` +
370 `If you are not the person who initiated this request, please ignore this email.\n\n` +
374 const emailPayload: EmailPayload = {
376 subject: 'Verify your PeerTube email',
380 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
383 addUserBlockJob (user: UserModel, blocked: boolean, reason?: string) {
384 const reasonString = reason ? ` for the following reason: ${reason}` : ''
385 const blockedWord = blocked ? 'blocked' : 'unblocked'
386 const blockedString = `Your account ${user.username} on ${CONFIG.WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
388 const text = 'Hi,\n\n' +
394 const to = user.email
395 const emailPayload: EmailPayload = {
397 subject: '[PeerTube] Account ' + blockedWord,
401 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
404 addContactFormJob (fromEmail: string, fromName: string, body: string) {
405 const text = 'Hello dear admin,\n\n' +
406 fromName + ' sent you a message' +
407 '\n\n---------------------------------------\n\n' +
409 '\n\n---------------------------------------\n\n' +
413 const emailPayload: EmailPayload = {
414 fromDisplayName: fromEmail,
416 to: [ CONFIG.ADMIN.EMAIL ],
417 subject: '[PeerTube] Contact form submitted',
421 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
424 sendMail (options: EmailPayload) {
425 if (!Emailer.isEnabled()) {
426 throw new Error('Cannot send mail because SMTP is not configured.')
429 const fromDisplayName = options.fromDisplayName
430 ? options.fromDisplayName
431 : CONFIG.WEBSERVER.HOST
433 return this.transporter.sendMail({
434 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`,
435 replyTo: options.replyTo,
436 to: options.to.join(','),
437 subject: options.subject,
442 private dieOnConnectionFailure (err?: Error) {
443 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
447 static get Instance () {
448 return this.instance || (this.instance = new this())
452 // ---------------------------------------------------------------------------