1 import { readFileSync } from 'fs-extra'
2 import { isArray, merge } from 'lodash'
3 import { createTransport, Transporter } from 'nodemailer'
4 import { join } from 'path'
5 import { root } from '@shared/core-utils'
6 import { EmailPayload } from '@shared/models'
7 import { SendEmailDefaultOptions } from '../../shared/models/server/emailer.model'
8 import { isTestOrDevInstance } from '../helpers/core-utils'
9 import { bunyanLogger, logger } from '../helpers/logger'
10 import { CONFIG, isEmailEnabled } from '../initializers/config'
11 import { WEBSERVER } from '../initializers/constants'
12 import { MUser } from '../types/models'
13 import { JobQueue } from './job-queue'
15 const Email = require('email-templates')
19 private static instance: Emailer
20 private initialized = false
21 private transporter: Transporter
23 private constructor () {
27 // Already initialized
28 if (this.initialized === true) return
29 this.initialized = true
31 if (!isEmailEnabled()) {
32 if (!isTestOrDevInstance()) {
33 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
39 if (CONFIG.SMTP.TRANSPORT === 'smtp') this.initSMTPTransport()
40 else if (CONFIG.SMTP.TRANSPORT === 'sendmail') this.initSendmailTransport()
43 async checkConnection () {
44 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
46 logger.info('Testing SMTP server...')
49 const success = await this.transporter.verify()
50 if (success !== true) this.warnOnConnectionFailure()
52 logger.info('Successfully connected to SMTP server.')
54 this.warnOnConnectionFailure(err)
58 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
59 const emailPayload: EmailPayload = {
60 template: 'password-reset',
62 subject: 'Reset your account password',
69 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
72 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
73 const emailPayload: EmailPayload = {
74 template: 'password-create',
76 subject: 'Create your account password',
83 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
86 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
87 const emailPayload: EmailPayload = {
88 template: 'verify-email',
90 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
97 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
100 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
101 const reasonString = reason ? ` for the following reason: ${reason}` : ''
102 const blockedWord = blocked ? 'blocked' : 'unblocked'
104 const to = user.email
105 const emailPayload: EmailPayload = {
107 subject: 'Account ' + blockedWord,
108 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
111 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
114 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
115 const emailPayload: EmailPayload = {
116 template: 'contact-form',
117 to: [ CONFIG.ADMIN.EMAIL ],
118 replyTo: `"${fromName}" <${fromEmail}>`,
119 subject: `(contact form) ${subject}`,
125 // There are not notification preferences for the contact form
126 hideNotificationPreferences: true
130 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
133 async sendMail (options: EmailPayload) {
134 if (!isEmailEnabled()) {
135 throw new Error('Cannot send mail because SMTP is not configured.')
138 const fromDisplayName = options.from
140 : CONFIG.INSTANCE.NAME
142 const email = new Email({
146 { selector: 'img', format: 'skip' },
147 { selector: 'a', options: { hideLinkHrefIfSameAsText: true } }
151 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
153 transport: this.transporter,
155 root: join(root(), 'dist', 'server', 'lib', 'emails')
157 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
160 const toEmails = isArray(options.to)
164 for (const to of toEmails) {
165 const baseOptions: SendEmailDefaultOptions = {
170 subject: options.subject,
171 replyTo: options.replyTo
173 locals: { // default variables available in all templates
176 instanceName: CONFIG.INSTANCE.NAME,
178 subject: options.subject
182 // overridden/new variables given for a specific template in the payload
183 const sendOptions = merge(baseOptions, options)
185 await email.send(sendOptions)
186 .then(res => logger.debug('Sent email.', { res }))
187 .catch(err => logger.error('Error in email sender.', { err }))
191 private warnOnConnectionFailure (err?: Error) {
192 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
195 private initSMTPTransport () {
196 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
199 if (CONFIG.SMTP.CA_FILE) {
201 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
206 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
208 user: CONFIG.SMTP.USERNAME,
209 pass: CONFIG.SMTP.PASSWORD
213 this.transporter = createTransport({
214 host: CONFIG.SMTP.HOSTNAME,
215 port: CONFIG.SMTP.PORT,
216 secure: CONFIG.SMTP.TLS,
217 debug: CONFIG.LOG.LEVEL === 'debug',
218 logger: bunyanLogger as any,
219 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
225 private initSendmailTransport () {
226 logger.info('Using sendmail to send emails')
228 this.transporter = createTransport({
231 path: CONFIG.SMTP.SENDMAIL,
236 static get Instance () {
237 return this.instance || (this.instance = new this())
241 // ---------------------------------------------------------------------------