]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/emailer.ts
Use bullmq job dependency
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
CommitLineData
d95d1559 1import { readFileSync } from 'fs-extra'
d26836cd 2import { isArray, merge } from 'lodash'
ecb4e35f 3import { createTransport, Transporter } from 'nodemailer'
d95d1559 4import { join } from 'path'
9452d4fd 5import { root } from '@shared/core-utils'
d26836cd 6import { EmailPayload } 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'
d26836cd 12import { 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,
df4c603d
RK
65 resetPasswordUrl
66 }
cef534ed
C
67 }
68
bd911b54 69 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
cef534ed
C
70 }
71
df4c603d 72 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
45f1bd72 73 const emailPayload: EmailPayload = {
df4c603d 74 template: 'password-create',
45f1bd72 75 to: [ to ],
df4c603d
RK
76 subject: 'Create your account password',
77 locals: {
78 username,
79 createPasswordUrl
80 }
45f1bd72
JL
81 }
82
bd911b54 83 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
45f1bd72
JL
84 }
85
963023ab 86 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
cef534ed 87 const emailPayload: EmailPayload = {
df4c603d 88 template: 'verify-email',
cef534ed 89 to: [ to ],
2e4b8ae4 90 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
df4c603d 91 locals: {
963023ab 92 username,
df4c603d
RK
93 verifyEmailUrl
94 }
cef534ed
C
95 }
96
bd911b54 97 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
cef534ed
C
98 }
99
453e83ea 100 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
eacb25c4
C
101 const reasonString = reason ? ` for the following reason: ${reason}` : ''
102 const blockedWord = blocked ? 'blocked' : 'unblocked'
eacb25c4
C
103
104 const to = user.email
105 const emailPayload: EmailPayload = {
106 to: [ to ],
df4c603d 107 subject: 'Account ' + blockedWord,
2e4b8ae4 108 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
eacb25c4
C
109 }
110
bd911b54 111 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
eacb25c4
C
112 }
113
4e9fa5b7 114 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
a4101923 115 const emailPayload: EmailPayload = {
df4c603d 116 template: 'contact-form',
a4101923 117 to: [ CONFIG.ADMIN.EMAIL ],
df4c603d
RK
118 replyTo: `"${fromName}" <${fromEmail}>`,
119 subject: `(contact form) ${subject}`,
120 locals: {
121 fromName,
122 fromEmail,
b9cf3fb6
C
123 body,
124
125 // There are not notification preferences for the contact form
126 hideNotificationPreferences: true
df4c603d 127 }
a4101923
C
128 }
129
bd911b54 130 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
a4101923
C
131 }
132
47f6cb31 133 async sendMail (options: EmailPayload) {
4c1c1709 134 if (!isEmailEnabled()) {
eaaf316f
C
135 logger.info('Cannot send mail because SMTP is not configured.')
136 return
ecb4e35f
C
137 }
138
df4c603d
RK
139 const fromDisplayName = options.from
140 ? options.from
2e4b8ae4 141 : CONFIG.INSTANCE.NAME
4759fedc 142
df4c603d
RK
143 const email = new Email({
144 send: true,
3c7ddd7d
C
145 htmlToText: {
146 selectors: [
147 { selector: 'img', format: 'skip' },
e85a36cb 148 { selector: 'a', options: { hideLinkHrefIfSameAsText: true } }
3c7ddd7d
C
149 ]
150 },
df4c603d
RK
151 message: {
152 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
153 },
154 transport: this.transporter,
155 views: {
03fc1928 156 root: join(root(), 'dist', 'server', 'lib', 'emails')
df4c603d
RK
157 },
158 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
159 })
160
d26836cd
C
161 const toEmails = isArray(options.to)
162 ? options.to
163 : [ options.to ]
164
165 for (const to of toEmails) {
cae2df6b
C
166 const baseOptions: SendEmailDefaultOptions = {
167 template: 'common',
168 message: {
169 to,
170 from: options.from,
171 subject: options.subject,
172 replyTo: options.replyTo
173 },
174 locals: { // default variables available in all templates
175 WEBSERVER,
176 EMAIL: CONFIG.EMAIL,
177 instanceName: CONFIG.INSTANCE.NAME,
178 text: options.text,
179 subject: options.subject
180 }
181 }
182
7a4fd56c 183 // overridden/new variables given for a specific template in the payload
cae2df6b
C
184 const sendOptions = merge(baseOptions, options)
185
186 await email.send(sendOptions)
03fc1928
C
187 .then(res => logger.debug('Sent email.', { res }))
188 .catch(err => logger.error('Error in email sender.', { err }))
47f6cb31 189 }
ecb4e35f
C
190 }
191
75594f47 192 private warnOnConnectionFailure (err?: Error) {
d5b7d911 193 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
ecb4e35f
C
194 }
195
448487a6
C
196 private initSMTPTransport () {
197 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
198
199 let tls
200 if (CONFIG.SMTP.CA_FILE) {
201 tls = {
202 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
203 }
204 }
205
206 let auth
207 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
208 auth = {
209 user: CONFIG.SMTP.USERNAME,
210 pass: CONFIG.SMTP.PASSWORD
211 }
212 }
213
214 this.transporter = createTransport({
215 host: CONFIG.SMTP.HOSTNAME,
216 port: CONFIG.SMTP.PORT,
217 secure: CONFIG.SMTP.TLS,
218 debug: CONFIG.LOG.LEVEL === 'debug',
219 logger: bunyanLogger as any,
220 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
221 tls,
222 auth
223 })
224 }
225
226 private initSendmailTransport () {
227 logger.info('Using sendmail to send emails')
228
229 this.transporter = createTransport({
230 sendmail: true,
231 newline: 'unix',
b7a27f28 232 path: CONFIG.SMTP.SENDMAIL,
40a8c0a4 233 logger: bunyanLogger
448487a6
C
234 })
235 }
236
ecb4e35f
C
237 static get Instance () {
238 return this.instance || (this.instance = new this())
239 }
240}
241
242// ---------------------------------------------------------------------------
243
244export {
8dc8a34e 245 Emailer
ecb4e35f 246}