我正在编写一些 C# 代码来发送电子邮件(通过 Mailjet/Azure)。它确实发送了电子邮件,但由于某种原因,在单步执行代码时我从未通过这行代码....
MailjetResponse response = await client.PostAsync(request);
它只是在那个时候挂起。知道为什么吗?同样,邮件发送成功!
public static async Task<bool> SendEmailWithAttachment(string toAddress, string subject, string messageBody, bool sendBCCYesNo, bool sendFromInfoAddressYesNo, MemoryStream attachment = null, string attachmentFilename = null)
{
bool successYesNo = true;
try
{
MailjetClient client = new MailjetClient("xxxxxx", "xxxxx")
{
Version = ApiVersion.V3_1,
};
MailjetRequest request = new MailjetRequest
{
Resource = Send.Resource,
}
.Property(Send.Messages, new JArray {
new JObject {
{"From", new JObject {
{"Email", "xxxxx@xxxxx.com"},
{"Name", "xxxxx"}
}},
{"To", new JArray {
new JObject {
{"Email", toAddress},
{"Name", toAddress}
}
}},
{"Subject", subject},
{"TextPart", messageBody},
{"HTMLPart", messageBody}
}
});
MailjetResponse response = await client.PostAsync(request);
if (response.IsSuccessStatusCode) // I never get to this point
{
:
我正在使用这个调用代码....
if (Utility.SendEmailWithAttachment("xxxxx@xxxxx.com", "Test Email", "Test Body", false, false,
po, "AAA.pdf").Result == false)
{
lblStatus.Text = "Email send failure. Please contact support.";
return false;
}
有趣的是,当我运行示例 mailjet 提供的代码时,我的电子邮件发送正常并且我确实到达了 PostAsync 之后的行。据我所知,唯一的主要区别是我使用的是返回 bool 值的任务,而不仅仅是任务。这是 mailjet 提供的工作正常的代码....
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
MailjetClient client = new MailjetClient("xxxx", "xxxx")
{
Version = ApiVersion.V3_1,
};
MailjetRequest request = new MailjetRequest
{
Resource = Send.Resource,
}
.Property(Send.Messages, new JArray {
new JObject {
{"From", new JObject {
{"Email", "xxxx@xxxx.com"},
{"Name", "xxxx"}
}},
{"To", new JArray {
new JObject {
{"Email", "xxxx@xxxx.com"},
{"Name", "xxxx"}
}
}},
{"Subject", "Your email flight plan!"},
{"TextPart", "Dear passenger 1, welcome to Mailjet! May the delivery force be with you!"},
{"HTMLPart", "<h3>Dear passenger 1, welcome to <a href='https://www.mailjet.com/'>Mailjet</a>!</h3><br />May the delivery force be with you!"}
}
});
MailjetResponse response = await client.PostAsync(request);
if (response.IsSuccessStatusCode) // this line is reached!
{
提前致谢!
请您参考如下方法:
试试下面的代码。一个好的经验法则是不要使用 *.Result 除非先等待。
if ((await Utility.SendEmailWithAttachment("xxxxx@xxxxx.com", "Test Email", "Test Body", false, false,
po, "AAA.pdf")) == false)
{
lblStatus.Text = "Email send failure. Please contact support.";
return false;
}
