]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/emailer.ts
3cdba5c76ec6681545adf432ff10184608bb844d
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
1 import { readFileSync } from 'fs-extra'
2 import { merge } from 'lodash'
3 import { createTransport, Transporter } from 'nodemailer'
4 import { join } from 'path'
5 import { toArray } from '@server/helpers/custom-validators/misc'
6 import { root } from '@shared/core-utils'
7 import { EmailPayload } from '@shared/models'
8 import { SendEmailDefaultOptions } from '../../shared/models/server/emailer.model'
9 import { isTestOrDevInstance } from '../helpers/core-utils'
10 import { bunyanLogger, logger } from '../helpers/logger'
11 import { CONFIG, isEmailEnabled } from '../initializers/config'
12 import { WEBSERVER } from '../initializers/constants'
13 import { MUser } from '../types/models'
14 import { JobQueue } from './job-queue'
15
16 const Email = require('email-templates')
17
18 class Emailer {
19
20 private static instance: Emailer
21 private initialized = false
22 private transporter: Transporter
23
24 private constructor () {
25 }
26
27 init () {
28 // Already initialized
29 if (this.initialized === true) return
30 this.initialized = true
31
32 if (!isEmailEnabled()) {
33 if (!isTestOrDevInstance()) {
34 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
35 }
36
37 return
38 }
39
40 if (CONFIG.SMTP.TRANSPORT === 'smtp') this.initSMTPTransport()
41 else if (CONFIG.SMTP.TRANSPORT === 'sendmail') this.initSendmailTransport()
42 }
43
44 async checkConnection () {
45 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
46
47 logger.info('Testing SMTP server...')
48
49 try {
50 const success = await this.transporter.verify()
51 if (success !== true) this.warnOnConnectionFailure()
52
53 logger.info('Successfully connected to SMTP server.')
54 } catch (err) {
55 this.warnOnConnectionFailure(err)
56 }
57 }
58
59 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
60 const emailPayload: EmailPayload = {
61 template: 'password-reset',
62 to: [ to ],
63 subject: 'Reset your account password',
64 locals: {
65 username,
66 resetPasswordUrl
67 }
68 }
69
70 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
71 }
72
73 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
74 const emailPayload: EmailPayload = {
75 template: 'password-create',
76 to: [ to ],
77 subject: 'Create your account password',
78 locals: {
79 username,
80 createPasswordUrl
81 }
82 }
83
84 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
85 }
86
87 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
88 const emailPayload: EmailPayload = {
89 template: 'verify-email',
90 to: [ to ],
91 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
92 locals: {
93 username,
94 verifyEmailUrl
95 }
96 }
97
98 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
99 }
100
101 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
102 const reasonString = reason ? ` for the following reason: ${reason}` : ''
103 const blockedWord = blocked ? 'blocked' : 'unblocked'
104
105 const to = user.email
106 const emailPayload: EmailPayload = {
107 to: [ to ],
108 subject: 'Account ' + blockedWord,
109 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
110 }
111
112 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
113 }
114
115 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
116 const emailPayload: EmailPayload = {
117 template: 'contact-form',
118 to: [ CONFIG.ADMIN.EMAIL ],
119 replyTo: `"${fromName}" <${fromEmail}>`,
120 subject: `(contact form) ${subject}`,
121 locals: {
122 fromName,
123 fromEmail,
124 body,
125
126 // There are not notification preferences for the contact form
127 hideNotificationPreferences: true
128 }
129 }
130
131 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
132 }
133
134 async sendMail (options: EmailPayload) {
135 if (!isEmailEnabled()) {
136 logger.info('Cannot send mail because SMTP is not configured.')
137 return
138 }
139
140 const fromDisplayName = options.from
141 ? options.from
142 : CONFIG.INSTANCE.NAME
143
144 const email = new Email({
145 send: true,
146 htmlToText: {
147 selectors: [
148 { selector: 'img', format: 'skip' },
149 { selector: 'a', options: { hideLinkHrefIfSameAsText: true } }
150 ]
151 },
152 message: {
153 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
154 },
155 transport: this.transporter,
156 views: {
157 root: join(root(), 'dist', 'server', 'lib', 'emails')
158 },
159 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
160 })
161
162 const toEmails = toArray(options.to)
163
164 for (const to of toEmails) {
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
182 // overridden/new variables given for a specific template in the payload
183 const sendOptions = merge(baseOptions, options)
184
185 await email.send(sendOptions)
186 .then(res => logger.debug('Sent email.', { res }))
187 .catch(err => logger.error('Error in email sender.', { err }))
188 }
189 }
190
191 private warnOnConnectionFailure (err?: Error) {
192 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
193 }
194
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',
231 path: CONFIG.SMTP.SENDMAIL,
232 logger: bunyanLogger
233 })
234 }
235
236 static get Instance () {
237 return this.instance || (this.instance = new this())
238 }
239 }
240
241 // ---------------------------------------------------------------------------
242
243 export {
244 Emailer
245 }