无服务器Mailgun无法生成邮件

问题描述

我想将脚趾浸入Serverless中,看看是否可以生成一个通过Mailgun发送消息的功能。我的函数成功运行,并显示消息“ Go Serverless v1.0!您的函数已成功执行!”。但没有通过Mailgun发送消息:

我的handler.js:

[["year": "2020","value": ["January","February"]],["value": ["march","April"],"year": "2019"]]

我的serverless.yml非常简单:

'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!')
        };
};

我已经通过curl和通过AWS中的UI测试了该功能,但均未提供任何与mailgun相关的调试消息。

解决方法

我怀疑,由于.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',text: 'Testing some Mailgun awesomeness!'
    });

    return {
        statusCode: 200,text: msgBody})
    };
};