]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/emailer.ts
Merge branch 'release/4.0.0' into develop
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
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 { EmailPayload } from '@shared/models'
6 import { SendEmailDefaultOptions } from '../../shared/models/server/emailer.model'
7 import { isTestInstance, root } from '../helpers/core-utils'
8 import { bunyanLogger, logger } from '../helpers/logger'
9 import { CONFIG, isEmailEnabled } from '../initializers/config'
10 import { WEBSERVER } from '../initializers/constants'
11 import { MUser } from '../types/models'
12 import { JobQueue } from './job-queue'
13
14 const Email = require('email-templates')
15
16 class Emailer {
17
18 private static instance: Emailer
19 private initialized = false
20 private transporter: Transporter
21
22 private constructor () {
23 }
24
25 init () {
26 // Already initialized
27 if (this.initialized === true) return
28 this.initialized = true
29
30 if (!isEmailEnabled()) {
31 if (!isTestInstance()) {
32 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
33 }
34
35 return
36 }
37
38 if (CONFIG.SMTP.TRANSPORT === 'smtp') this.initSMTPTransport()
39 else if (CONFIG.SMTP.TRANSPORT === 'sendmail') this.initSendmailTransport()
40 }
41
42 async checkConnection () {
43 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
44
45 logger.info('Testing SMTP server...')
46
47 try {
48 const success = await this.transporter.verify()
49 if (success !== true) this.warnOnConnectionFailure()
50
51 logger.info('Successfully connected to SMTP server.')
52 } catch (err) {
53 this.warnOnConnectionFailure(err)
54 }
55 }
56
57 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
58 const emailPayload: EmailPayload = {
59 template: 'password-reset',
60 to: [ to ],
61 subject: 'Reset your account password',
62 locals: {
63 username,
64 resetPasswordUrl
65 }
66 }
67
68 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
69 }
70
71 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
72 const emailPayload: EmailPayload = {
73 template: 'password-create',
74 to: [ to ],
75 subject: 'Create your account password',
76 locals: {
77 username,
78 createPasswordUrl
79 }
80 }
81
82 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
83 }
84
85 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
86 const emailPayload: EmailPayload = {
87 template: 'verify-email',
88 to: [ to ],
89 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
90 locals: {
91 username,
92 verifyEmailUrl
93 }
94 }
95
96 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
97 }
98
99 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
100 const reasonString = reason ? ` for the following reason: ${reason}` : ''
101 const blockedWord = blocked ? 'blocked' : 'unblocked'
102
103 const to = user.email
104 const emailPayload: EmailPayload = {
105 to: [ to ],
106 subject: 'Account ' + blockedWord,
107 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
108 }
109
110 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
111 }
112
113 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
114 const emailPayload: EmailPayload = {
115 template: 'contact-form',
116 to: [ CONFIG.ADMIN.EMAIL ],
117 replyTo: `"${fromName}" <${fromEmail}>`,
118 subject: `(contact form) ${subject}`,
119 locals: {
120 fromName,
121 fromEmail,
122 body,
123
124 // There are not notification preferences for the contact form
125 hideNotificationPreferences: true
126 }
127 }
128
129 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
130 }
131
132 async sendMail (options: EmailPayload) {
133 if (!isEmailEnabled()) {
134 throw new Error('Cannot send mail because SMTP is not configured.')
135 }
136
137 const fromDisplayName = options.from
138 ? options.from
139 : CONFIG.INSTANCE.NAME
140
141 const email = new Email({
142 send: true,
143 message: {
144 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
145 },
146 transport: this.transporter,
147 views: {
148 root: join(root(), 'dist', 'server', 'lib', 'emails')
149 },
150 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
151 })
152
153 const toEmails = isArray(options.to)
154 ? options.to
155 : [ options.to ]
156
157 for (const to of toEmails) {
158 const baseOptions: SendEmailDefaultOptions = {
159 template: 'common',
160 message: {
161 to,
162 from: options.from,
163 subject: options.subject,
164 replyTo: options.replyTo
165 },
166 locals: { // default variables available in all templates
167 WEBSERVER,
168 EMAIL: CONFIG.EMAIL,
169 instanceName: CONFIG.INSTANCE.NAME,
170 text: options.text,
171 subject: options.subject
172 }
173 }
174
175 // overriden/new variables given for a specific template in the payload
176 const sendOptions = merge(baseOptions, options)
177
178 await email.send(sendOptions)
179 .then(res => logger.debug('Sent email.', { res }))
180 .catch(err => logger.error('Error in email sender.', { err }))
181 }
182 }
183
184 private warnOnConnectionFailure (err?: Error) {
185 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
186 }
187
188 private initSMTPTransport () {
189 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
190
191 let tls
192 if (CONFIG.SMTP.CA_FILE) {
193 tls = {
194 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
195 }
196 }
197
198 let auth
199 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
200 auth = {
201 user: CONFIG.SMTP.USERNAME,
202 pass: CONFIG.SMTP.PASSWORD
203 }
204 }
205
206 this.transporter = createTransport({
207 host: CONFIG.SMTP.HOSTNAME,
208 port: CONFIG.SMTP.PORT,
209 secure: CONFIG.SMTP.TLS,
210 debug: CONFIG.LOG.LEVEL === 'debug',
211 logger: bunyanLogger as any,
212 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
213 tls,
214 auth
215 })
216 }
217
218 private initSendmailTransport () {
219 logger.info('Using sendmail to send emails')
220
221 this.transporter = createTransport({
222 sendmail: true,
223 newline: 'unix',
224 path: CONFIG.SMTP.SENDMAIL,
225 logger: bunyanLogger
226 })
227 }
228
229 static get Instance () {
230 return this.instance || (this.instance = new this())
231 }
232 }
233
234 // ---------------------------------------------------------------------------
235
236 export {
237 Emailer
238 }