提问者:小点点

无服务器Mailgun不生成邮件


我想我应该尝试一下无服务器,看看是否可以生成一个通过Mailgun发送消息的函数。我的函数成功运行,并显示消息“Go Serverless V1.0!您的函数执行成功!”但不通过MailGun发送消息:

我的handler.js:

'use strict';
var mailgun = require('mailgun-js')({apiKey: 'xxx', domain: 'email.mydomain.co.uk'})

module.exports.hello = async event => {
        var data = {
            from: 'no-reply@email.mydomain.co.uk',
            to: 'me@somewhere.co.uk',
            subject: 'Hello',
            text: 'Testing some Mailgun awesomeness!'
        };

        mailgun.messages().send(data, function (error, body) {
            if(error)
            {
                    console.log(error)
            }
            console.log(body);
        });

        return {
            statusCode: 200,
            body: JSON.stringify('Go Serverless v1.0! Your function executed successfully!')
        };
};

我的Serverless.yml非常简单:

service: helloworld
provider:
  name: aws
  runtime: nodejs12.x
  region: eu-west-2
functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: post

我已经用curl和通过AWS中的UI测试了这个函数,但是都没有提供任何与MailGun相关的调试消息。


共1个答案

匿名用户

我怀疑,由于.send()方法是异步的,所以您的处理程序没有等待足够长的时间并在消息完成之前完成运行。

返回一个承诺(mailgun-js的API已经在生成承诺,您只需返回它们即可):

module.exports.hello = event => {
    return mailgun.messages().send({
        from: 'no-reply@email.mydomain.co.uk',
        to: 'me@somewhere.co.uk',
        subject: 'Hello',
        text: 'Testing some Mailgun awesomeness!'
    }).then(msgBody => {
        statusCode: 200,
        body: JSON.stringify({status: 'sent a message!', text: msgBody})
    });
};

当您自己返回一个实际的承诺时,async关键字就变得多余了。您可以以async/await样式重写相同的内容:

module.exports.hello = async event => {
    var msgBody = await mailgun.messages().send({
        from: 'no-reply@email.mydomain.co.uk',
        to: 'me@somewhere.co.uk',
        subject: 'Hello',
        text: 'Testing some Mailgun awesomeness!'
    });

    return {
        statusCode: 200,
        body: JSON.stringify({status: 'sent a message!', text: msgBody})
    };
};