]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/emailer.ts
Fix email logger typings
[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'
d26836cd 5import { EmailPayload } from '@shared/models'
cae2df6b 6import { SendEmailDefaultOptions } from '../../shared/models/server/emailer.model'
df4c603d 7import { isTestInstance, root } from '../helpers/core-utils'
05e67d62 8import { bunyanLogger, logger } from '../helpers/logger'
4c1c1709 9import { CONFIG, isEmailEnabled } from '../initializers/config'
6dd9de95 10import { WEBSERVER } from '../initializers/constants'
d26836cd 11import { MUser } from '../types/models'
d95d1559 12import { JobQueue } from './job-queue'
98b94643 13
df4c603d 14const Email = require('email-templates')
dee77e76 15
ecb4e35f
C
16class Emailer {
17
18 private static instance: Emailer
19 private initialized = false
20 private transporter: Transporter
21
a1587156
C
22 private constructor () {
23 }
ecb4e35f
C
24
25 init () {
26 // Already initialized
27 if (this.initialized === true) return
28 this.initialized = true
29
448487a6 30 if (!isEmailEnabled()) {
ecb4e35f
C
31 if (!isTestInstance()) {
32 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
33 }
ecb4e35f 34
448487a6 35 return
ed3f089c 36 }
448487a6
C
37
38 if (CONFIG.SMTP.TRANSPORT === 'smtp') this.initSMTPTransport()
39 else if (CONFIG.SMTP.TRANSPORT === 'sendmail') this.initSendmailTransport()
3b3b1820
C
40 }
41
75594f47 42 async checkConnection () {
ed3f089c 43 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
ecb4e35f 44
3d3441d6
C
45 logger.info('Testing SMTP server...')
46
ecb4e35f
C
47 try {
48 const success = await this.transporter.verify()
75594f47 49 if (success !== true) this.warnOnConnectionFailure()
ecb4e35f
C
50
51 logger.info('Successfully connected to SMTP server.')
52 } catch (err) {
75594f47 53 this.warnOnConnectionFailure(err)
ecb4e35f
C
54 }
55 }
56
963023ab 57 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
cef534ed 58 const emailPayload: EmailPayload = {
df4c603d 59 template: 'password-reset',
cef534ed 60 to: [ to ],
df4c603d
RK
61 subject: 'Reset your account password',
62 locals: {
963023ab 63 username,
df4c603d
RK
64 resetPasswordUrl
65 }
cef534ed
C
66 }
67
68 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
69 }
70
df4c603d 71 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
45f1bd72 72 const emailPayload: EmailPayload = {
df4c603d 73 template: 'password-create',
45f1bd72 74 to: [ to ],
df4c603d
RK
75 subject: 'Create your account password',
76 locals: {
77 username,
78 createPasswordUrl
79 }
45f1bd72
JL
80 }
81
82 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
83 }
84
963023ab 85 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
cef534ed 86 const emailPayload: EmailPayload = {
df4c603d 87 template: 'verify-email',
cef534ed 88 to: [ to ],
2e4b8ae4 89 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
df4c603d 90 locals: {
963023ab 91 username,
df4c603d
RK
92 verifyEmailUrl
93 }
cef534ed
C
94 }
95
96 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
97 }
98
453e83ea 99 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
eacb25c4
C
100 const reasonString = reason ? ` for the following reason: ${reason}` : ''
101 const blockedWord = blocked ? 'blocked' : 'unblocked'
eacb25c4
C
102
103 const to = user.email
104 const emailPayload: EmailPayload = {
105 to: [ to ],
df4c603d 106 subject: 'Account ' + blockedWord,
2e4b8ae4 107 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
eacb25c4
C
108 }
109
110 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
111 }
112
4e9fa5b7 113 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
a4101923 114 const emailPayload: EmailPayload = {
df4c603d 115 template: 'contact-form',
a4101923 116 to: [ CONFIG.ADMIN.EMAIL ],
df4c603d
RK
117 replyTo: `"${fromName}" <${fromEmail}>`,
118 subject: `(contact form) ${subject}`,
119 locals: {
120 fromName,
121 fromEmail,
b9cf3fb6
C
122 body,
123
124 // There are not notification preferences for the contact form
125 hideNotificationPreferences: true
df4c603d 126 }
a4101923
C
127 }
128
129 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
130 }
131
47f6cb31 132 async sendMail (options: EmailPayload) {
4c1c1709 133 if (!isEmailEnabled()) {
ecb4e35f
C
134 throw new Error('Cannot send mail because SMTP is not configured.')
135 }
136
df4c603d
RK
137 const fromDisplayName = options.from
138 ? options.from
2e4b8ae4 139 : CONFIG.INSTANCE.NAME
4759fedc 140
df4c603d
RK
141 const email = new Email({
142 send: true,
143 message: {
144 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
145 },
146 transport: this.transporter,
147 views: {
03fc1928 148 root: join(root(), 'dist', 'server', 'lib', 'emails')
df4c603d
RK
149 },
150 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
151 })
152
d26836cd
C
153 const toEmails = isArray(options.to)
154 ? options.to
155 : [ options.to ]
156
157 for (const to of toEmails) {
cae2df6b
C
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)
03fc1928
C
179 .then(res => logger.debug('Sent email.', { res }))
180 .catch(err => logger.error('Error in email sender.', { err }))
47f6cb31 181 }
ecb4e35f
C
182 }
183
75594f47 184 private warnOnConnectionFailure (err?: Error) {
d5b7d911 185 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
ecb4e35f
C
186 }
187
448487a6
C
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',
b7a27f28 224 path: CONFIG.SMTP.SENDMAIL,
40a8c0a4 225 logger: bunyanLogger
448487a6
C
226 })
227 }
228
ecb4e35f
C
229 static get Instance () {
230 return this.instance || (this.instance = new this())
231 }
232}
233
234// ---------------------------------------------------------------------------
235
236export {
8dc8a34e 237 Emailer
ecb4e35f 238}