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/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'
9 import { MCommentOwnerVideo, MVideo, MVideoAbuseVideo, MVideoAccountLight, MVideoBlacklistVideo } from '../typings/models/video'
10 import { MActorFollowActors, MActorFollowFollowingFullFollowerAccount, MUser } from '../typings/models'
11 import { MVideoImport, MVideoImportVideo } from '@server/typings/models/video/video-import'
13 type SendEmailOptions = {
18 fromDisplayName?: string
24 private static instance: Emailer
25 private initialized = false
26 private transporter: Transporter
28 private constructor () {}
31 // Already initialized
32 if (this.initialized === true) return
33 this.initialized = true
35 if (Emailer.isEnabled()) {
36 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
39 if (CONFIG.SMTP.CA_FILE) {
41 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
46 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
48 user: CONFIG.SMTP.USERNAME,
49 pass: CONFIG.SMTP.PASSWORD
53 this.transporter = createTransport({
54 host: CONFIG.SMTP.HOSTNAME,
55 port: CONFIG.SMTP.PORT,
56 secure: CONFIG.SMTP.TLS,
57 debug: CONFIG.LOG.LEVEL === 'debug',
58 logger: bunyanLogger as any,
59 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
64 if (!isTestInstance()) {
65 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
71 return !!CONFIG.SMTP.HOSTNAME && !!CONFIG.SMTP.PORT
74 async checkConnectionOrDie () {
75 if (!this.transporter) return
77 logger.info('Testing SMTP server...')
80 const success = await this.transporter.verify()
81 if (success !== true) this.dieOnConnectionFailure()
83 logger.info('Successfully connected to SMTP server.')
85 this.dieOnConnectionFailure(err)
89 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
90 const channelName = video.VideoChannel.getDisplayName()
91 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
93 const text = `Hi dear user,\n\n` +
94 `Your subscription ${channelName} just published a new video: ${video.name}` +
96 `You can view it on ${videoUrl} ` +
99 `${CONFIG.EMAIL.BODY.SIGNATURE}`
101 const emailPayload: EmailPayload = {
103 subject: CONFIG.EMAIL.SUBJECT.PREFIX + channelName + ' just published a new video',
107 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
110 addNewFollowNotification (to: string[], actorFollow: MActorFollowFollowingFullFollowerAccount, followType: 'account' | 'channel') {
111 const followerName = actorFollow.ActorFollower.Account.getDisplayName()
112 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
114 const text = `Hi dear user,\n\n` +
115 `Your ${followType} ${followingName} has a new subscriber: ${followerName}` +
118 `${CONFIG.EMAIL.BODY.SIGNATURE}`
120 const emailPayload: EmailPayload = {
122 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New follower on your channel ' + followingName,
126 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
129 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
130 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
132 const text = `Hi dear admin,\n\n` +
133 `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}` +
136 `${CONFIG.EMAIL.BODY.SIGNATURE}`
138 const emailPayload: EmailPayload = {
140 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New instance follower',
144 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
147 myVideoPublishedNotification (to: string[], video: MVideo) {
148 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
150 const text = `Hi dear user,\n\n` +
151 `Your video ${video.name} has been published.` +
153 `You can view it on ${videoUrl} ` +
156 `${CONFIG.EMAIL.BODY.SIGNATURE}`
158 const emailPayload: EmailPayload = {
160 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Your video ${video.name} is published`,
164 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
167 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
168 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
170 const text = `Hi dear user,\n\n` +
171 `Your video import ${videoImport.getTargetIdentifier()} is finished.` +
173 `You can view the imported video on ${videoUrl} ` +
176 `${CONFIG.EMAIL.BODY.SIGNATURE}`
178 const emailPayload: EmailPayload = {
180 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Your video import ${videoImport.getTargetIdentifier()} is finished`,
184 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
187 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
188 const importUrl = WEBSERVER.URL + '/my-account/video-imports'
190 const text = `Hi dear user,\n\n` +
191 `Your video import ${videoImport.getTargetIdentifier()} encountered an error.` +
193 `See your videos import dashboard for more information: ${importUrl}` +
196 `${CONFIG.EMAIL.BODY.SIGNATURE}`
198 const emailPayload: EmailPayload = {
200 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Your video import ${videoImport.getTargetIdentifier()} encountered an error`,
204 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
207 addNewCommentOnMyVideoNotification (to: string[], comment: MCommentOwnerVideo) {
208 const accountName = comment.Account.getDisplayName()
209 const video = comment.Video
210 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
212 const text = `Hi dear user,\n\n` +
213 `A new comment has been posted by ${accountName} on your video ${video.name}` +
215 `You can view it on ${commentUrl} ` +
218 `${CONFIG.EMAIL.BODY.SIGNATURE}`
220 const emailPayload: EmailPayload = {
222 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New comment on your video ' + video.name,
226 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
229 addNewCommentMentionNotification (to: string[], comment: MCommentOwnerVideo) {
230 const accountName = comment.Account.getDisplayName()
231 const video = comment.Video
232 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
234 const text = `Hi dear user,\n\n` +
235 `${accountName} mentioned you on video ${video.name}` +
237 `You can view the comment on ${commentUrl} ` +
240 `${CONFIG.EMAIL.BODY.SIGNATURE}`
242 const emailPayload: EmailPayload = {
244 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Mention on video ' + video.name,
248 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
251 addVideoAbuseModeratorsNotification (to: string[], videoAbuse: MVideoAbuseVideo) {
252 const videoUrl = WEBSERVER.URL + videoAbuse.Video.getWatchStaticPath()
254 const text = `Hi,\n\n` +
255 `${WEBSERVER.HOST} received an abuse for the following video ${videoUrl}\n\n` +
257 `${CONFIG.EMAIL.BODY.SIGNATURE}`
259 const emailPayload: EmailPayload = {
261 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Received a video abuse',
265 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
268 addVideoAutoBlacklistModeratorsNotification (to: string[], video: MVideo) {
269 const VIDEO_AUTO_BLACKLIST_URL = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
270 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
272 const text = `Hi,\n\n` +
273 `A recently added video was auto-blacklisted and requires moderator review before publishing.` +
275 `You can view it and take appropriate action on ${videoUrl}` +
277 `A full list of auto-blacklisted videos can be reviewed here: ${VIDEO_AUTO_BLACKLIST_URL}` +
280 `${CONFIG.EMAIL.BODY.SIGNATURE}`
282 const emailPayload: EmailPayload = {
284 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'An auto-blacklisted video is awaiting review',
288 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
291 addNewUserRegistrationNotification (to: string[], user: MUser) {
292 const text = `Hi,\n\n` +
293 `User ${user.username} just registered on ${WEBSERVER.HOST} PeerTube instance.\n\n` +
295 `${CONFIG.EMAIL.BODY.SIGNATURE}`
297 const emailPayload: EmailPayload = {
299 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New user registration on ' + WEBSERVER.HOST,
303 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
306 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
307 const videoName = videoBlacklist.Video.name
308 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
310 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
311 const blockedString = `Your video ${videoName} (${videoUrl} on ${WEBSERVER.HOST} has been blacklisted${reasonString}.`
313 const text = 'Hi,\n\n' +
317 `${CONFIG.EMAIL.BODY.SIGNATURE}`
319 const emailPayload: EmailPayload = {
321 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Video ${videoName} blacklisted`,
325 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
328 addVideoUnblacklistNotification (to: string[], video: MVideo) {
329 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
331 const text = 'Hi,\n\n' +
332 `Your video ${video.name} (${videoUrl}) on ${WEBSERVER.HOST} has been unblacklisted.` +
335 `${CONFIG.EMAIL.BODY.SIGNATURE}`
337 const emailPayload: EmailPayload = {
339 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Video ${video.name} unblacklisted`,
343 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
346 addPasswordResetEmailJob (to: string, resetPasswordUrl: string) {
347 const text = `Hi dear user,\n\n` +
348 `A reset password procedure for your account ${to} has been requested on ${WEBSERVER.HOST} ` +
349 `Please follow this link to reset it: ${resetPasswordUrl}\n\n` +
350 `If you are not the person who initiated this request, please ignore this email.\n\n` +
352 `${CONFIG.EMAIL.BODY.SIGNATURE}`
354 const emailPayload: EmailPayload = {
356 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Reset your password',
360 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
363 addVerifyEmailJob (to: string, verifyEmailUrl: string) {
364 const text = `Welcome to PeerTube,\n\n` +
365 `To start using PeerTube on ${WEBSERVER.HOST} you must verify your email! ` +
366 `Please follow this link to verify this email belongs to you: ${verifyEmailUrl}\n\n` +
367 `If you are not the person who initiated this request, please ignore this email.\n\n` +
369 `${CONFIG.EMAIL.BODY.SIGNATURE}`
371 const emailPayload: EmailPayload = {
373 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Verify your email',
377 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
380 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
381 const reasonString = reason ? ` for the following reason: ${reason}` : ''
382 const blockedWord = blocked ? 'blocked' : 'unblocked'
383 const blockedString = `Your account ${user.username} on ${WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
385 const text = 'Hi,\n\n' +
389 `${CONFIG.EMAIL.BODY.SIGNATURE}`
391 const to = user.email
392 const emailPayload: EmailPayload = {
394 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Account ' + blockedWord,
398 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
401 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
402 const text = 'Hello dear admin,\n\n' +
403 fromName + ' sent you a message' +
404 '\n\n---------------------------------------\n\n' +
406 '\n\n---------------------------------------\n\n' +
410 const emailPayload: EmailPayload = {
411 fromDisplayName: fromEmail,
413 to: [ CONFIG.ADMIN.EMAIL ],
414 subject: CONFIG.EMAIL.SUBJECT.PREFIX + subject,
418 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
421 sendMail (options: EmailPayload) {
422 if (!Emailer.isEnabled()) {
423 throw new Error('Cannot send mail because SMTP is not configured.')
426 const fromDisplayName = options.fromDisplayName
427 ? options.fromDisplayName
430 return this.transporter.sendMail({
431 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`,
432 replyTo: options.replyTo,
433 to: options.to.join(','),
434 subject: options.subject,
439 private dieOnConnectionFailure (err?: Error) {
440 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
444 static get Instance () {
445 return this.instance || (this.instance = new this())
449 // ---------------------------------------------------------------------------