我正在尝试从alexa技能向Mailgun(授权ID)发送电子邮件通知。在节点环境中隔离启动时,代码工作正常。但是在Lambda上执行时无法发送邮件。
以下是代码段:
var User= this.attributes['UserName']; /*session variable is working fine...*/
var data = {
from: 'xxxxxxxx', /*Mailgun sandbox*/
to: 'zzzzzzzz', /* Authorized mail ID*/
subject: 'Request',
text: `Hi, ${Alias} is waiting for you.`
};
mailgun.messages().send(data, function(error, body) {
console.log(body);
});
this.response.speak('A message has been sent to ${User}.');
this.emit(':responseReady');
编辑:我的环境变量设置如下:
/* Parameters for MAILGUN*/
var api_key = process.env.MAILGUN_API_KEY;
var domain = process.env.MAILGUN_DOMAIN;
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
Lambda函数设置正确为:
exports.handle = function(event, context) { /* "index.handler" would call
exports.handler in index.js.*/
var alexa = Alexa.handler(event, context);
alexa.appId = appId;
alexa.registerHandlers(newSessionHandler, greetingHandler, aliasHandler, addressHandler, daysHandler1, accessHandler, daysHandler2, hostnameHandler, hostHandler, facilityHandler1, facilityHandler2, hsschrHandler, hsschostHandler); /* List of handlers */
alexa.execute();
};
lambda代码执行没有问题,整个代码被执行,响应从Alexa收到,如#34;已发送消息"。但实际上并非如此。理想情况下,它应首先发送邮件然后发出响应。
我正在使用Apex进行lambda部署,并且我已经在project.json中正确设置了环境变量" environment":
{
"MAILGUN_API_KEY": "${MAILGUN_API_KEY}",
"MAILGUN_DOMAIN": "${MAILGUN_DOMAIN}"
}
答案 0 :(得分:0)
我不能说为什么没有发送电子邮件,但我的建议是重新构造代码有点像这样:
mailgun.messages().send(data, (error, body) => {
if (error) {
console.log('something went wrong');
console.log(error);
} else {
console.log('message sent')
console.log(body);
this.response.speak('A message has been sent to ${User}.');
this.emit(':responseReady');
}
});
有几点需要注意:
this.response.speak
和this.emit
现在发生在回调函数中,因此Alexa只会在邮件成功发送后发言,看起来是您想要的行为function(error, body) {}
更改为箭头函数(error, body) => {}
。这基本上允许您在回调中使用this
并从外部范围引用this
如果发送邮件仍有问题,至少现在它会被记录,您可以进一步调试。