-
-
Notifications
You must be signed in to change notification settings - Fork 305
/
Copy pathhelper.service.email.ts
executable file
·81 lines (72 loc) · 2.09 KB
/
helper.service.email.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* @file Email service
* @module processor/helper/email.service
* @author Surmon <https://github.com/surmon-china>
*/
import nodemailer from 'nodemailer'
import { Injectable } from '@nestjs/common'
import { getMessageFromNormalError } from '@app/transformers/error.transformer'
import { createLogger } from '@app/utils/logger'
import { isDevEnv } from '@app/app.environment'
import * as APP_CONFIG from '@app/app.config'
const logger = createLogger({ scope: 'EmailService', time: isDevEnv })
export interface EmailOptions {
to: string
subject: string
text: string
html: string
}
@Injectable()
export class EmailService {
private transporter: nodemailer.Transporter
private clientIsValid: boolean
constructor() {
this.transporter = nodemailer.createTransport({
host: APP_CONFIG.EMAIL.host,
port: APP_CONFIG.EMAIL.port,
secure: false,
auth: {
user: APP_CONFIG.EMAIL.account,
pass: APP_CONFIG.EMAIL.password
}
})
this.verifyClient()
}
private verifyClient(): void {
return this.transporter.verify((error) => {
if (error) {
this.clientIsValid = false
setTimeout(this.verifyClient.bind(this), 1000 * 60 * 30)
logger.error(`client initialization failed! retry after 30 mins`, '|', getMessageFromNormalError(error))
} else {
this.clientIsValid = true
logger.success('client initialized.')
}
})
}
public sendMail(mailOptions: EmailOptions) {
if (!this.clientIsValid) {
logger.warn('send failed! (initialization failed)')
return false
}
this.transporter.sendMail(
{
...mailOptions,
from: APP_CONFIG.EMAIL.from
},
(error, info) => {
if (error) {
logger.failure(`send failed!`, getMessageFromNormalError(error))
} else {
logger.success('send succeeded.', info.messageId, info.response)
}
}
)
}
public sendMailAs(prefix: string, mailOptions: EmailOptions) {
return this.sendMail({
...mailOptions,
subject: `[${prefix}] ${mailOptions.subject}`
})
}
}