1 import { createTransport, Transporter } from 'nodemailer'
2 import { UserRight } from '../../shared/models/users'
3 import { isTestInstance } from '../helpers/core-utils'
4 import { bunyanLogger, logger } from '../helpers/logger'
5 import { CONFIG } from '../initializers'
6 import { UserModel } from '../models/account/user'
7 import { VideoModel } from '../models/video/video'
8 import { JobQueue } from './job-queue'
9 import { EmailPayload } from './job-queue/handlers/email'
10 import { readFileSync } from 'fs'
14 private static instance: Emailer
15 private initialized = false
16 private transporter: Transporter
18 private constructor () {}
21 // Already initialized
22 if (this.initialized === true) return
23 this.initialized = true
25 if (CONFIG.SMTP.HOSTNAME && CONFIG.SMTP.PORT) {
26 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
29 if (CONFIG.SMTP.CA_FILE) {
31 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
36 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
38 user: CONFIG.SMTP.USERNAME,
39 pass: CONFIG.SMTP.PASSWORD
43 this.transporter = createTransport({
44 host: CONFIG.SMTP.HOSTNAME,
45 port: CONFIG.SMTP.PORT,
46 secure: CONFIG.SMTP.TLS,
47 debug: CONFIG.LOG.LEVEL === 'debug',
48 logger: bunyanLogger as any,
49 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
54 if (!isTestInstance()) {
55 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
60 async checkConnectionOrDie () {
61 if (!this.transporter) return
63 logger.info('Testing SMTP server...')
66 const success = await this.transporter.verify()
67 if (success !== true) this.dieOnConnectionFailure()
69 logger.info('Successfully connected to SMTP server.')
71 this.dieOnConnectionFailure(err)
75 addForgetPasswordEmailJob (to: string, resetPasswordUrl: string) {
76 const text = `Hi dear user,\n\n` +
77 `It seems you forgot your password on ${CONFIG.WEBSERVER.HOST}! ` +
78 `Please follow this link to reset it: ${resetPasswordUrl}\n\n` +
79 `If you are not the person who initiated this request, please ignore this email.\n\n` +
83 const emailPayload: EmailPayload = {
85 subject: 'Reset your PeerTube password',
89 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
92 async addVideoAbuseReportJob (videoId: number) {
93 const video = await VideoModel.load(videoId)
94 if (!video) throw new Error('Unknown Video id during Abuse report.')
96 const text = `Hi,\n\n` +
97 `Your instance received an abuse for the following video ${video.url}\n\n` +
101 const to = await UserModel.listEmailsWithRight(UserRight.MANAGE_VIDEO_ABUSES)
102 const emailPayload: EmailPayload = {
104 subject: '[PeerTube] Received a video abuse',
108 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
111 async addVideoBlacklistReportJob (videoId: number, reason?: string) {
112 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
113 if (!video) throw new Error('Unknown Video id during Blacklist report.')
115 if (video.remote === true) return
117 const user = await UserModel.loadById(video.VideoChannel.Account.userId)
119 const reasonString = reason ? ` for the following reason: ${reason}` : ''
120 const blockedString = `Your video ${video.name} on ${CONFIG.WEBSERVER.HOST} has been blacklisted${reasonString}.`
122 const text = 'Hi,\n\n' +
128 const to = user.email
129 const emailPayload: EmailPayload = {
131 subject: `[PeerTube] Video ${video.name} blacklisted`,
135 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
138 async addVideoUnblacklistReportJob (videoId: number) {
139 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
140 if (!video) throw new Error('Unknown Video id during Blacklist report.')
142 if (video.remote === true) return
144 const user = await UserModel.loadById(video.VideoChannel.Account.userId)
146 const text = 'Hi,\n\n' +
147 `Your video ${video.name} on ${CONFIG.WEBSERVER.HOST} has been unblacklisted.` +
152 const to = user.email
153 const emailPayload: EmailPayload = {
155 subject: `[PeerTube] Video ${video.name} unblacklisted`,
159 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
162 addUserBlockJob (user: UserModel, blocked: boolean, reason?: string) {
163 const reasonString = reason ? ` for the following reason: ${reason}` : ''
164 const blockedWord = blocked ? 'blocked' : 'unblocked'
165 const blockedString = `Your account ${user.username} on ${CONFIG.WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
167 const text = 'Hi,\n\n' +
173 const to = user.email
174 const emailPayload: EmailPayload = {
176 subject: '[PeerTube] Account ' + blockedWord,
180 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
183 sendMail (to: string[], subject: string, text: string) {
184 if (!this.transporter) {
185 throw new Error('Cannot send mail because SMTP is not configured.')
188 return this.transporter.sendMail({
189 from: CONFIG.SMTP.FROM_ADDRESS,
196 private dieOnConnectionFailure (err?: Error) {
197 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
201 static get Instance () {
202 return this.instance || (this.instance = new this())
206 // ---------------------------------------------------------------------------