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