使用 Typescript 和类发送 mailgun 消息

时间:2021-02-07 08:01:52

标签: javascript typescript mailgun

我正在尝试给自己发送一封电子邮件,只是为了测试以确保我已正确设置所有内容。我没有收到任何错误消息,因此无法真正找到我犯错的地方。

以下是我的 Mailer.js 代码:

import mg, { Mailgun } from "mailgun-js"
import utils = require('./utils')

interface MailerConfig {
  apiKey: string,
  domain: string
}

export class Mailer {
  private mailgun: Mailgun;

  constructor(
    private config: MailerConfig, 
    private fromEmail: string = 'test <hello@test.com>' 
  ) {
    this.mailgun = mg({
      apiKey: this.config.apiKey,
      domain: this.config.domain
    })
  }

  async sendMessage(email: string, subject: string, templateName: string, templateVars: Object): Promise<any> {
    const mailData = {
      from: this.fromEmail,
      // to: email,
      to: 'test@test.com',
      subject,
      template: templateName,
      ...templateVars
    }

    return this.mailgun.messages().send(mailData, (err, body) => {
        if(err || !body) {
          console.log(err)
          console.error('Error:', err)
        }

        console.log('Successfully sent email.')
    })
  }
}

我正在尝试使用以下内容发送消息:

const sendEmailToRandomUser = async (): Promise<void> => {
  try {
    const randomUser: UserDocument = await pickRandomUser()

    // Send winner email using email from user document
    const mailer = new Mailer({
      apiKey: process.env.MAILGUN_API_KEY || '',
      domain: process.env.MAILGUN_DOMAIN || 'test.domain.com'
    })

    mailer.sendMessage(
      randomUser.email, 
      'You\'ve won!', 
      'wewm-please-complete-winner', 
      { 
        'v:claimPrizeUrl': 'test'
      }
    ).then((res) => {
      console.log(res)
      console.log('exit process')
      // exit automated scheduler
      process.exit(1)
    }).catch(err => console.log(err))

    console.log('end of sendEmailToRandomUser')
    // if everything goes well and email is sent
    // save user property as having received said email
  } catch (err) {
    console.log(err)
  }
}

sendEmailToRandomUser()

我得到以下输出:

end of sendEmailToRandomUser
undefined
exit process

我哪里出错了?

1 个答案:

答案 0 :(得分:0)

我改为将调用函数的格式改为如下:

    const response = await mailer.sendMessage(
      randomUser.email,
      'You\'ve won!',
      'wewm-please-complete-winner',
      {
        'v:claimPrizeUrl': `${process.env.HOSTNAME}/.../.../.../${winningUser.wonEverythingToken}`
      },
      () => onEmailSendCompleteCallback('test@test.com')
    )

通过以下方式传递 onComplete 回调以在完成时触发:

sendMessage(
    email: string,
    subject: string,
    templateName: string,
    templateVars: Object,
    onEmailSentComplete?: Function
  ): Promise<any> {
    // create mailData info for email
    const mailData = {
      from: this.fromEmail,
      // to: email,
      to: 'test@test.com',  //TODO: make this user email
      subject,
      template: templateName,
      ...templateVars
    }

    return this.mailgun.messages().send(mailData, (err, body) => {
      if (err || !body) {
        console.error('Error:', err)
      }

      console.log('Successfully sent email to Win Everything We Make Winner!')

      if (onEmailSentComplete) {
        console.log('email sent!')
        onEmailSentComplete()
      }
    })
  }
相关问题