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 myVideoPublishedNotification (to: string[], video: VideoModel) {
133 const videoUrl = CONFIG.WEBSERVER.URL + video.getWatchStaticPath()
135 const text = `Hi dear user,\n\n` +
136 `Your video ${video.name} has been published.` +
138 `You can view it on ${videoUrl} ` +
143 const emailPayload: EmailPayload = {
145 subject: `Your video ${video.name} is published`,
149 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
152 myVideoImportSuccessNotification (to: string[], videoImport: VideoImportModel) {
153 const videoUrl = CONFIG.WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
155 const text = `Hi dear user,\n\n` +
156 `Your video import ${videoImport.getTargetIdentifier()} is finished.` +
158 `You can view the imported video on ${videoUrl} ` +
163 const emailPayload: EmailPayload = {
165 subject: `Your video import ${videoImport.getTargetIdentifier()} is finished`,
169 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
172 myVideoImportErrorNotification (to: string[], videoImport: VideoImportModel) {
173 const importUrl = CONFIG.WEBSERVER.URL + '/my-account/video-imports'
175 const text = `Hi dear user,\n\n` +
176 `Your video import ${videoImport.getTargetIdentifier()} encountered an error.` +
178 `See your videos import dashboard for more information: ${importUrl}` +
183 const emailPayload: EmailPayload = {
185 subject: `Your video import ${videoImport.getTargetIdentifier()} encountered an error`,
189 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
192 addNewCommentOnMyVideoNotification (to: string[], comment: VideoCommentModel) {
193 const accountName = comment.Account.getDisplayName()
194 const video = comment.Video
195 const commentUrl = CONFIG.WEBSERVER.URL + comment.getCommentStaticPath()
197 const text = `Hi dear user,\n\n` +
198 `A new comment has been posted by ${accountName} on your video ${video.name}` +
200 `You can view it on ${commentUrl} ` +
205 const emailPayload: EmailPayload = {
207 subject: 'New comment on your video ' + video.name,
211 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
214 addNewCommentMentionNotification (to: string[], comment: VideoCommentModel) {
215 const accountName = comment.Account.getDisplayName()
216 const video = comment.Video
217 const commentUrl = CONFIG.WEBSERVER.URL + comment.getCommentStaticPath()
219 const text = `Hi dear user,\n\n` +
220 `${accountName} mentioned you on video ${video.name}` +
222 `You can view the comment on ${commentUrl} ` +
227 const emailPayload: EmailPayload = {
229 subject: 'Mention on video ' + video.name,
233 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
236 addVideoAbuseModeratorsNotification (to: string[], videoAbuse: VideoAbuseModel) {
237 const videoUrl = CONFIG.WEBSERVER.URL + videoAbuse.Video.getWatchStaticPath()
239 const text = `Hi,\n\n` +
240 `${CONFIG.WEBSERVER.HOST} received an abuse for the following video ${videoUrl}\n\n` +
244 const emailPayload: EmailPayload = {
246 subject: '[PeerTube] Received a video abuse',
250 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
253 addNewUserRegistrationNotification (to: string[], user: UserModel) {
254 const text = `Hi,\n\n` +
255 `User ${user.username} just registered on ${CONFIG.WEBSERVER.HOST} PeerTube instance.\n\n` +
259 const emailPayload: EmailPayload = {
261 subject: '[PeerTube] New user registration on ' + CONFIG.WEBSERVER.HOST,
265 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
268 addVideoBlacklistNotification (to: string[], videoBlacklist: VideoBlacklistModel) {
269 const videoName = videoBlacklist.Video.name
270 const videoUrl = CONFIG.WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
272 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
273 const blockedString = `Your video ${videoName} (${videoUrl} on ${CONFIG.WEBSERVER.HOST} has been blacklisted${reasonString}.`
275 const text = 'Hi,\n\n' +
281 const emailPayload: EmailPayload = {
283 subject: `[PeerTube] Video ${videoName} blacklisted`,
287 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
290 addVideoUnblacklistNotification (to: string[], video: VideoModel) {
291 const videoUrl = CONFIG.WEBSERVER.URL + video.getWatchStaticPath()
293 const text = 'Hi,\n\n' +
294 `Your video ${video.name} (${videoUrl}) on ${CONFIG.WEBSERVER.HOST} has been unblacklisted.` +
299 const emailPayload: EmailPayload = {
301 subject: `[PeerTube] Video ${video.name} unblacklisted`,
305 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
308 addPasswordResetEmailJob (to: string, resetPasswordUrl: string) {
309 const text = `Hi dear user,\n\n` +
310 `A reset password procedure for your account ${to} has been requested on ${CONFIG.WEBSERVER.HOST} ` +
311 `Please follow this link to reset it: ${resetPasswordUrl}\n\n` +
312 `If you are not the person who initiated this request, please ignore this email.\n\n` +
316 const emailPayload: EmailPayload = {
318 subject: 'Reset your PeerTube password',
322 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
325 addVerifyEmailJob (to: string, verifyEmailUrl: string) {
326 const text = `Welcome to PeerTube,\n\n` +
327 `To start using PeerTube on ${CONFIG.WEBSERVER.HOST} you must verify your email! ` +
328 `Please follow this link to verify this email belongs to you: ${verifyEmailUrl}\n\n` +
329 `If you are not the person who initiated this request, please ignore this email.\n\n` +
333 const emailPayload: EmailPayload = {
335 subject: 'Verify your PeerTube email',
339 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
342 addUserBlockJob (user: UserModel, blocked: boolean, reason?: string) {
343 const reasonString = reason ? ` for the following reason: ${reason}` : ''
344 const blockedWord = blocked ? 'blocked' : 'unblocked'
345 const blockedString = `Your account ${user.username} on ${CONFIG.WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
347 const text = 'Hi,\n\n' +
353 const to = user.email
354 const emailPayload: EmailPayload = {
356 subject: '[PeerTube] Account ' + blockedWord,
360 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
363 addContactFormJob (fromEmail: string, fromName: string, body: string) {
364 const text = 'Hello dear admin,\n\n' +
365 fromName + ' sent you a message' +
366 '\n\n---------------------------------------\n\n' +
368 '\n\n---------------------------------------\n\n' +
372 const emailPayload: EmailPayload = {
373 fromDisplayName: fromEmail,
375 to: [ CONFIG.ADMIN.EMAIL ],
376 subject: '[PeerTube] Contact form submitted',
380 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
383 sendMail (options: EmailPayload) {
384 if (!Emailer.isEnabled()) {
385 throw new Error('Cannot send mail because SMTP is not configured.')
388 const fromDisplayName = options.fromDisplayName
389 ? options.fromDisplayName
390 : CONFIG.WEBSERVER.HOST
392 return this.transporter.sendMail({
393 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`,
394 replyTo: options.replyTo,
395 to: options.to.join(','),
396 subject: options.subject,
401 private dieOnConnectionFailure (err?: Error) {
402 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
406 static get Instance () {
407 return this.instance || (this.instance = new this())
411 // ---------------------------------------------------------------------------