1 import { readFileSync } from 'fs-extra'
2 import { merge } from 'lodash'
3 import { createTransport, Transporter } from 'nodemailer'
4 import { join } from 'path'
5 import { toArray } from '@server/helpers/custom-validators/misc'
6 import { root } from '@shared/core-utils'
7 import { EmailPayload } from '@shared/models'
8 import { SendEmailDefaultOptions } from '../../shared/models/server/emailer.model'
9 import { isTestOrDevInstance } from '../helpers/core-utils'
10 import { bunyanLogger, logger } from '../helpers/logger'
11 import { CONFIG, isEmailEnabled } from '../initializers/config'
12 import { WEBSERVER } from '../initializers/constants'
13 import { MUser } from '../types/models'
14 import { JobQueue } from './job-queue'
16 const Email = require('email-templates')
20 private static instance: Emailer
21 private initialized = false
22 private transporter: Transporter
24 private constructor () {
28 // Already initialized
29 if (this.initialized === true) return
30 this.initialized = true
32 if (!isEmailEnabled()) {
33 if (!isTestOrDevInstance()) {
34 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
40 if (CONFIG.SMTP.TRANSPORT === 'smtp') this.initSMTPTransport()
41 else if (CONFIG.SMTP.TRANSPORT === 'sendmail') this.initSendmailTransport()
44 async checkConnection () {
45 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
47 logger.info('Testing SMTP server...')
50 const success = await this.transporter.verify()
51 if (success !== true) this.warnOnConnectionFailure()
53 logger.info('Successfully connected to SMTP server.')
55 this.warnOnConnectionFailure(err)
59 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
60 const emailPayload: EmailPayload = {
61 template: 'password-reset',
63 subject: 'Reset your account password',
70 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
73 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
74 const emailPayload: EmailPayload = {
75 template: 'password-create',
77 subject: 'Create your account password',
84 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
87 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
88 const emailPayload: EmailPayload = {
89 template: 'verify-email',
91 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
98 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
101 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
102 const reasonString = reason ? ` for the following reason: ${reason}` : ''
103 const blockedWord = blocked ? 'blocked' : 'unblocked'
105 const to = user.email
106 const emailPayload: EmailPayload = {
108 subject: 'Account ' + blockedWord,
109 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
112 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
115 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
116 const emailPayload: EmailPayload = {
117 template: 'contact-form',
118 to: [ CONFIG.ADMIN.EMAIL ],
119 replyTo: `"${fromName}" <${fromEmail}>`,
120 subject: `(contact form) ${subject}`,
126 // There are not notification preferences for the contact form
127 hideNotificationPreferences: true
131 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
134 async sendMail (options: EmailPayload) {
135 if (!isEmailEnabled()) {
136 logger.info('Cannot send mail because SMTP is not configured.')
140 const fromDisplayName = options.from
142 : CONFIG.INSTANCE.NAME
144 const email = new Email({
148 { selector: 'img', format: 'skip' },
149 { selector: 'a', options: { hideLinkHrefIfSameAsText: true } }
153 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
155 transport: this.transporter,
157 root: join(root(), 'dist', 'server', 'lib', 'emails')
159 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
162 const toEmails = toArray(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 // ---------------------------------------------------------------------------