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-extra'
14 private static instance: Emailer
15 private initialized = false
16 private transporter: Transporter
17 private enabled = false
19 private constructor () {}
22 // Already initialized
23 if (this.initialized === true) return
24 this.initialized = true
26 if (CONFIG.SMTP.HOSTNAME && CONFIG.SMTP.PORT) {
27 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
30 if (CONFIG.SMTP.CA_FILE) {
32 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
37 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
39 user: CONFIG.SMTP.USERNAME,
40 pass: CONFIG.SMTP.PASSWORD
44 this.transporter = createTransport({
45 host: CONFIG.SMTP.HOSTNAME,
46 port: CONFIG.SMTP.PORT,
47 secure: CONFIG.SMTP.TLS,
48 debug: CONFIG.LOG.LEVEL === 'debug',
49 logger: bunyanLogger as any,
50 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
57 if (!isTestInstance()) {
58 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
67 async checkConnectionOrDie () {
68 if (!this.transporter) return
70 logger.info('Testing SMTP server...')
73 const success = await this.transporter.verify()
74 if (success !== true) this.dieOnConnectionFailure()
76 logger.info('Successfully connected to SMTP server.')
78 this.dieOnConnectionFailure(err)
82 addForgetPasswordEmailJob (to: string, resetPasswordUrl: string) {
83 const text = `Hi dear user,\n\n` +
84 `It seems you forgot your password on ${CONFIG.WEBSERVER.HOST}! ` +
85 `Please follow this link to reset it: ${resetPasswordUrl}\n\n` +
86 `If you are not the person who initiated this request, please ignore this email.\n\n` +
90 const emailPayload: EmailPayload = {
92 subject: 'Reset your PeerTube password',
96 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
99 addVerifyEmailJob (to: string, verifyEmailUrl: string) {
100 const text = `Welcome to PeerTube,\n\n` +
101 `To start using PeerTube on ${CONFIG.WEBSERVER.HOST} you must verify your email! ` +
102 `Please follow this link to verify this email belongs to you: ${verifyEmailUrl}\n\n` +
103 `If you are not the person who initiated this request, please ignore this email.\n\n` +
107 const emailPayload: EmailPayload = {
109 subject: 'Verify your PeerTube email',
113 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
116 async addVideoAbuseReportJob (videoId: number) {
117 const video = await VideoModel.load(videoId)
118 if (!video) throw new Error('Unknown Video id during Abuse report.')
120 const text = `Hi,\n\n` +
121 `Your instance received an abuse for the following video ${video.url}\n\n` +
125 const to = await UserModel.listEmailsWithRight(UserRight.MANAGE_VIDEO_ABUSES)
126 const emailPayload: EmailPayload = {
128 subject: '[PeerTube] Received a video abuse',
132 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
135 async addVideoBlacklistReportJob (videoId: number, reason?: string) {
136 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
137 if (!video) throw new Error('Unknown Video id during Blacklist report.')
139 if (video.remote === true) return
141 const user = await UserModel.loadById(video.VideoChannel.Account.userId)
143 const reasonString = reason ? ` for the following reason: ${reason}` : ''
144 const blockedString = `Your video ${video.name} on ${CONFIG.WEBSERVER.HOST} has been blacklisted${reasonString}.`
146 const text = 'Hi,\n\n' +
152 const to = user.email
153 const emailPayload: EmailPayload = {
155 subject: `[PeerTube] Video ${video.name} blacklisted`,
159 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
162 async addVideoUnblacklistReportJob (videoId: number) {
163 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
164 if (!video) throw new Error('Unknown Video id during Blacklist report.')
166 if (video.remote === true) return
168 const user = await UserModel.loadById(video.VideoChannel.Account.userId)
170 const text = 'Hi,\n\n' +
171 `Your video ${video.name} on ${CONFIG.WEBSERVER.HOST} has been unblacklisted.` +
176 const to = user.email
177 const emailPayload: EmailPayload = {
179 subject: `[PeerTube] Video ${video.name} unblacklisted`,
183 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
186 addUserBlockJob (user: UserModel, blocked: boolean, reason?: string) {
187 const reasonString = reason ? ` for the following reason: ${reason}` : ''
188 const blockedWord = blocked ? 'blocked' : 'unblocked'
189 const blockedString = `Your account ${user.username} on ${CONFIG.WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
191 const text = 'Hi,\n\n' +
197 const to = user.email
198 const emailPayload: EmailPayload = {
200 subject: '[PeerTube] Account ' + blockedWord,
204 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
207 sendMail (to: string[], subject: string, text: string) {
208 if (!this.transporter) {
209 throw new Error('Cannot send mail because SMTP is not configured.')
212 return this.transporter.sendMail({
213 from: CONFIG.SMTP.FROM_ADDRESS,
220 private dieOnConnectionFailure (err?: Error) {
221 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
225 static get Instance () {
226 return this.instance || (this.instance = new this())
230 // ---------------------------------------------------------------------------