我最初使用AWS SES从我的Lambda发送邮件,但它有非常慢的交付。
然后,我决定切换到MailJet,并使用他们的API发送邮件。我使用的是NuGet包,API的V3.1,以及来自MailJet的示例代码来发送邮件异步。
public async Task<bool> SendEmailAsync(EmailModel model)
{
Boolean sent = false;
MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("EmailAPIKey"), Environment.GetEnvironmentVariable("EmailAPISecret"))
{
Version = ApiVersion.V3_1,
};
MailjetRequest request = new MailjetRequest
{
Resource = Send.Resource,
}.Property(Send.Messages, new JArray {
new JObject {
{"From", new JObject {
{"Email", Environment.GetEnvironmentVariable("SenderEmail")},
{"Name", Environment.GetEnvironmentVariable("SenderEmailName")}
}
},
{"HTMLPart", model.EmailHtmlBody},
{"Subject", model.EmailSubject},
{"TextPart", model.EmailTextBody},
{"To", new JArray {
new JObject {
{"Email", model.EmailTo},
{"Name", model.EmailTo}
}
}}
}
});
try
{
MailjetResponse response = await client.PostAsync(request);
if (response.IsSuccessStatusCode)
{
sent = true;
LambdaLogger.Log(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
LambdaLogger.Log(response.GetData().ToString());
}
else
{
sent = false;
LambdaLogger.Log(string.Format("StatusCode: {0}\n", response.StatusCode));
LambdaLogger.Log(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
LambdaLogger.Log(response.GetData().ToString());
LambdaLogger.Log(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
}
}
catch (Exception mailFail)
{
sent = false;
LambdaLogger.Log(string.Format("Failed: {0}\n", mailFail.Message.ToString() + " : " + mailFail.InnerException.Message.ToString()));
}
return sent;
}当我在本地测试代码时,一切都很好。
当我将lambda部署到AWS并调用发送邮件的方法时,如果发送邮件,则完全是随机的。我猜是异步部分因为某种原因而失败了,我希望有人能帮助我解决这个问题,因为现在我被困在这个问题上。
或者,如果有人能告诉我如何让亚马逊SES毫不拖延地发送。
发布于 2020-07-31 13:12:46
从问题中:
它是完全随机的
从评论中可以看到:
看起来,lambda只是继续运行,而不是等待MailJet的回复。
这听起来像是异步/等待问题,但可能不是您所想的那样。请注意,您正在正确地等待MailJet操作的结果:
MailjetResponse response = await client.PostAsync(request);但这只是在这个方法中。这个方法当然是async
public async Task<bool> SendEmailAsync(EmailModel model)当你调用这个方法时,你会await它吗?调用它的方法,也应该是async。你在等那个吗?基本上,你是“异步一直向下”吗
它听起来像是在代码库的某个地方,有一个异步操作正在被调用,然后被遗忘。
https://stackoverflow.com/questions/63191256
复制相似问题