1 import { readFileSync } from 'fs-extra'
2 import { merge } from 'lodash'
3 import { createTransport, Transporter } from 'nodemailer'
4 import { join } from 'path'
5 import { arrayify, root } from '@shared/core-utils'
6 import { EmailPayload, UserRegistrationState } 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 { MRegistration, 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',
67 hideNotificationPreferencesLink: true
71 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
74 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
75 const emailPayload: EmailPayload = {
76 template: 'password-create',
78 subject: 'Create your account password',
83 hideNotificationPreferencesLink: true
87 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
90 addVerifyEmailJob (options: {
92 isRegistrationRequest: boolean
94 verifyEmailUrl: string
96 const { username, isRegistrationRequest, to, verifyEmailUrl } = options
98 const emailPayload: EmailPayload = {
99 template: 'verify-email',
101 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
105 isRegistrationRequest,
107 hideNotificationPreferencesLink: true
111 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
114 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
115 const reasonString = reason ? ` for the following reason: ${reason}` : ''
116 const blockedWord = blocked ? 'blocked' : 'unblocked'
118 const to = user.email
119 const emailPayload: EmailPayload = {
121 subject: 'Account ' + blockedWord,
122 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
125 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
128 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
129 const emailPayload: EmailPayload = {
130 template: 'contact-form',
131 to: [ CONFIG.ADMIN.EMAIL ],
132 replyTo: `"${fromName}" <${fromEmail}>`,
133 subject: `(contact form) ${subject}`,
139 // There are not notification preferences for the contact form
140 hideNotificationPreferencesLink: true
144 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
147 addUserRegistrationRequestProcessedJob (registration: MRegistration) {
150 if (registration.state === UserRegistrationState.ACCEPTED) {
151 template = 'user-registration-request-accepted'
152 subject = `Your registration request for ${registration.username} has been accepted`
154 template = 'user-registration-request-rejected'
155 subject = `Your registration request for ${registration.username} has been rejected`
158 const to = registration.email
159 const emailPayload: EmailPayload = {
164 username: registration.username,
165 moderationResponse: registration.moderationResponse,
166 loginLink: WEBSERVER.URL + '/login'
170 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
173 async sendMail (options: EmailPayload) {
174 if (!isEmailEnabled()) {
175 logger.info('Cannot send mail because SMTP is not configured.')
179 const fromDisplayName = options.from
181 : CONFIG.INSTANCE.NAME
183 const email = new Email({
187 { selector: 'img', format: 'skip' },
188 { selector: 'a', options: { hideLinkHrefIfSameAsText: true } }
192 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
194 transport: this.transporter,
196 root: join(root(), 'dist', 'server', 'lib', 'emails')
198 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
201 const toEmails = arrayify(options.to)
203 for (const to of toEmails) {
204 const baseOptions: SendEmailDefaultOptions = {
209 subject: options.subject,
210 replyTo: options.replyTo
212 locals: { // default variables available in all templates
215 instanceName: CONFIG.INSTANCE.NAME,
217 subject: options.subject
221 // overridden/new variables given for a specific template in the payload
222 const sendOptions = merge(baseOptions, options)
224 await email.send(sendOptions)
225 .then(res => logger.debug('Sent email.', { res }))
226 .catch(err => logger.error('Error in email sender.', { err }))
230 private warnOnConnectionFailure (err?: Error) {
231 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
234 private initSMTPTransport () {
235 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
238 if (CONFIG.SMTP.CA_FILE) {
240 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
245 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
247 user: CONFIG.SMTP.USERNAME,
248 pass: CONFIG.SMTP.PASSWORD
252 this.transporter = createTransport({
253 host: CONFIG.SMTP.HOSTNAME,
254 port: CONFIG.SMTP.PORT,
255 secure: CONFIG.SMTP.TLS,
256 debug: CONFIG.LOG.LEVEL === 'debug',
257 logger: bunyanLogger as any,
258 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
264 private initSendmailTransport () {
265 logger.info('Using sendmail to send emails')
267 this.transporter = createTransport({
270 path: CONFIG.SMTP.SENDMAIL,
275 static get Instance () {
276 return this.instance || (this.instance = new this())
280 // ---------------------------------------------------------------------------