]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/emailer.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
CommitLineData
d95d1559 1import { readFileSync } from 'fs-extra'
2ec349aa 2import { merge } from 'lodash'
ecb4e35f 3import { createTransport, Transporter } from 'nodemailer'
d95d1559 4import { join } from 'path'
690bb8f9 5import { arrayify, root } from '@shared/core-utils'
e364e31e 6import { EmailPayload, UserRegistrationState } from '@shared/models'
cae2df6b 7import { SendEmailDefaultOptions } from '../../shared/models/server/emailer.model'
9452d4fd 8import { isTestOrDevInstance } from '../helpers/core-utils'
05e67d62 9import { bunyanLogger, logger } from '../helpers/logger'
4c1c1709 10import { CONFIG, isEmailEnabled } from '../initializers/config'
6dd9de95 11import { WEBSERVER } from '../initializers/constants'
e364e31e 12import { MRegistration, MUser } from '../types/models'
d95d1559 13import { JobQueue } from './job-queue'
98b94643 14
df4c603d 15const Email = require('email-templates')
dee77e76 16
ecb4e35f
C
17class Emailer {
18
19 private static instance: Emailer
20 private initialized = false
21 private transporter: Transporter
22
a1587156
C
23 private constructor () {
24 }
ecb4e35f
C
25
26 init () {
27 // Already initialized
28 if (this.initialized === true) return
29 this.initialized = true
30
448487a6 31 if (!isEmailEnabled()) {
9452d4fd 32 if (!isTestOrDevInstance()) {
ecb4e35f
C
33 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
34 }
ecb4e35f 35
448487a6 36 return
ed3f089c 37 }
448487a6
C
38
39 if (CONFIG.SMTP.TRANSPORT === 'smtp') this.initSMTPTransport()
40 else if (CONFIG.SMTP.TRANSPORT === 'sendmail') this.initSendmailTransport()
3b3b1820
C
41 }
42
75594f47 43 async checkConnection () {
ed3f089c 44 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
ecb4e35f 45
3d3441d6
C
46 logger.info('Testing SMTP server...')
47
ecb4e35f
C
48 try {
49 const success = await this.transporter.verify()
75594f47 50 if (success !== true) this.warnOnConnectionFailure()
ecb4e35f
C
51
52 logger.info('Successfully connected to SMTP server.')
53 } catch (err) {
75594f47 54 this.warnOnConnectionFailure(err)
ecb4e35f
C
55 }
56 }
57
963023ab 58 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
cef534ed 59 const emailPayload: EmailPayload = {
df4c603d 60 template: 'password-reset',
cef534ed 61 to: [ to ],
df4c603d
RK
62 subject: 'Reset your account password',
63 locals: {
963023ab 64 username,
e364e31e
C
65 resetPasswordUrl,
66
67 hideNotificationPreferencesLink: true
df4c603d 68 }
cef534ed
C
69 }
70
bd911b54 71 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
cef534ed
C
72 }
73
df4c603d 74 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
45f1bd72 75 const emailPayload: EmailPayload = {
df4c603d 76 template: 'password-create',
45f1bd72 77 to: [ to ],
df4c603d
RK
78 subject: 'Create your account password',
79 locals: {
80 username,
e364e31e
C
81 createPasswordUrl,
82
83 hideNotificationPreferencesLink: true
df4c603d 84 }
45f1bd72
JL
85 }
86
bd911b54 87 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
45f1bd72
JL
88 }
89
e364e31e
C
90 addVerifyEmailJob (options: {
91 username: string
92 isRegistrationRequest: boolean
93 to: string
94 verifyEmailUrl: string
95 }) {
96 const { username, isRegistrationRequest, to, verifyEmailUrl } = options
97
cef534ed 98 const emailPayload: EmailPayload = {
df4c603d 99 template: 'verify-email',
cef534ed 100 to: [ to ],
2e4b8ae4 101 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
df4c603d 102 locals: {
963023ab 103 username,
e364e31e
C
104 verifyEmailUrl,
105 isRegistrationRequest,
106
107 hideNotificationPreferencesLink: true
df4c603d 108 }
cef534ed
C
109 }
110
bd911b54 111 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
cef534ed
C
112 }
113
453e83ea 114 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
eacb25c4
C
115 const reasonString = reason ? ` for the following reason: ${reason}` : ''
116 const blockedWord = blocked ? 'blocked' : 'unblocked'
eacb25c4
C
117
118 const to = user.email
119 const emailPayload: EmailPayload = {
120 to: [ to ],
df4c603d 121 subject: 'Account ' + blockedWord,
2e4b8ae4 122 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
eacb25c4
C
123 }
124
bd911b54 125 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
eacb25c4
C
126 }
127
4e9fa5b7 128 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
a4101923 129 const emailPayload: EmailPayload = {
df4c603d 130 template: 'contact-form',
a4101923 131 to: [ CONFIG.ADMIN.EMAIL ],
df4c603d
RK
132 replyTo: `"${fromName}" <${fromEmail}>`,
133 subject: `(contact form) ${subject}`,
134 locals: {
135 fromName,
136 fromEmail,
b9cf3fb6
C
137 body,
138
139 // There are not notification preferences for the contact form
e364e31e
C
140 hideNotificationPreferencesLink: true
141 }
142 }
143
144 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
145 }
146
147 addUserRegistrationRequestProcessedJob (registration: MRegistration) {
148 let template: string
149 let subject: string
150 if (registration.state === UserRegistrationState.ACCEPTED) {
151 template = 'user-registration-request-accepted'
152 subject = `Your registration request for ${registration.username} has been accepted`
153 } else {
154 template = 'user-registration-request-rejected'
155 subject = `Your registration request for ${registration.username} has been rejected`
156 }
157
158 const to = registration.email
159 const emailPayload: EmailPayload = {
160 to: [ to ],
161 template,
162 subject,
163 locals: {
164 username: registration.username,
165 moderationResponse: registration.moderationResponse,
166 loginLink: WEBSERVER.URL + '/login'
df4c603d 167 }
a4101923
C
168 }
169
bd911b54 170 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
a4101923
C
171 }
172
47f6cb31 173 async sendMail (options: EmailPayload) {
4c1c1709 174 if (!isEmailEnabled()) {
eaaf316f
C
175 logger.info('Cannot send mail because SMTP is not configured.')
176 return
ecb4e35f
C
177 }
178
df4c603d
RK
179 const fromDisplayName = options.from
180 ? options.from
2e4b8ae4 181 : CONFIG.INSTANCE.NAME
4759fedc 182
df4c603d
RK
183 const email = new Email({
184 send: true,
3c7ddd7d
C
185 htmlToText: {
186 selectors: [
187 { selector: 'img', format: 'skip' },
e85a36cb 188 { selector: 'a', options: { hideLinkHrefIfSameAsText: true } }
3c7ddd7d
C
189 ]
190 },
df4c603d
RK
191 message: {
192 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
193 },
194 transport: this.transporter,
195 views: {
03fc1928 196 root: join(root(), 'dist', 'server', 'lib', 'emails')
df4c603d
RK
197 },
198 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
199 })
200
690bb8f9 201 const toEmails = arrayify(options.to)
d26836cd
C
202
203 for (const to of toEmails) {
cae2df6b
C
204 const baseOptions: SendEmailDefaultOptions = {
205 template: 'common',
206 message: {
207 to,
208 from: options.from,
209 subject: options.subject,
210 replyTo: options.replyTo
211 },
212 locals: { // default variables available in all templates
213 WEBSERVER,
214 EMAIL: CONFIG.EMAIL,
215 instanceName: CONFIG.INSTANCE.NAME,
216 text: options.text,
217 subject: options.subject
218 }
219 }
220
7a4fd56c 221 // overridden/new variables given for a specific template in the payload
cae2df6b
C
222 const sendOptions = merge(baseOptions, options)
223
224 await email.send(sendOptions)
03fc1928
C
225 .then(res => logger.debug('Sent email.', { res }))
226 .catch(err => logger.error('Error in email sender.', { err }))
47f6cb31 227 }
ecb4e35f
C
228 }
229
75594f47 230 private warnOnConnectionFailure (err?: Error) {
d5b7d911 231 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
ecb4e35f
C
232 }
233
448487a6
C
234 private initSMTPTransport () {
235 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
236
237 let tls
238 if (CONFIG.SMTP.CA_FILE) {
239 tls = {
240 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
241 }
242 }
243
244 let auth
245 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
246 auth = {
247 user: CONFIG.SMTP.USERNAME,
248 pass: CONFIG.SMTP.PASSWORD
249 }
250 }
251
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,
259 tls,
260 auth
261 })
262 }
263
264 private initSendmailTransport () {
265 logger.info('Using sendmail to send emails')
266
267 this.transporter = createTransport({
268 sendmail: true,
269 newline: 'unix',
b7a27f28 270 path: CONFIG.SMTP.SENDMAIL,
40a8c0a4 271 logger: bunyanLogger
448487a6
C
272 })
273 }
274
ecb4e35f
C
275 static get Instance () {
276 return this.instance || (this.instance = new this())
277 }
278}
279
280// ---------------------------------------------------------------------------
281
282export {
8dc8a34e 283 Emailer
ecb4e35f 284}