mailer.js 1.56 KB
Newer Older
abergavenny's avatar
abergavenny committed
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
import nodemailer from 'nodemailer'

class Mailer {
  constructor () {
    this._transport = null
    this._isTest = false
    this._isDisabled = false
  }

  async init (options = null, mode = null) {
    let transportOptions = options

    if (mode === null) this._isDisabled = true

    const isEmpty = !options?.host || !options?.port || !options?.user || !options?.host

    if (isEmpty || !options) {
      const account = await nodemailer.createTestAccount()

      transportOptions = {
        host: 'smtp.ethereal.email',
        port: 587,
        secure: false,
        auth: {
          user: account.user,
          pass: account.pass
        }
      }

      this._isTest = true
    }

    this._transport = nodemailer.createTransport(transportOptions)
  }

  async sendMail (to, subject, message, html = null) {
    try {
      if (!this._transport) throw new Error('Call Mailer.init()')

      const mail = {
        from: 'sender@example.com', // DEVINFO Hier die entsprechende Absenderadresse einfügen
        to,
        subject,
        text: message
      }

      if (this._isDisabled) {
        mail.from = 'sender@example.com'
        mail.to = 'receiver@example.com'
        mail.subject = 'Test Message Subject'
        mail.text = 'Test Message Body'
      }

      const info = await this._transport.sendMail(mail)

      console.log('LOG Message:', info)

      if (this._isTest) {
        console.log('LOG Test Account URL:', nodemailer.getTestMessageUrl(info))
      }
    } catch (error) {
      console.log('ERROR:', error.name)
    }
  }
}

export default Mailer