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