我正在使用 SendGrid 的 C# 客户端库,版本号为 9.27.0。
我唯一能发送电子邮件的方法是在我的代码末尾添加 Wait()
。
我知道 await
运算符是一个承诺,在异步方法完成后返回到代码中的某个点。
但是,为什么需要添加 Wait()
呢?那不是将异步方法转换为同步方法吗?如果真是这样,那么将其设置为异步有什么意义呢?
Program.cs
static void Main(string[] args) {
//var customerImport = new CustomerImport();
//customerImport.DoImport();
var mailClient = new MailClient();
var recipients = new List<string>();
recipients.Add("test@lobbycentral.com");
//Never sends an email
var response = mailClient.SendMail("noreply@lobbycentral.com", recipients, "Test email", "This is a test of the new SG client", false);
//Will send an email
mailClient.SendMail("noreply@lobbycentral.com", recipients, "Test email", "This is a test of the new SG client", false).Wait();
}
MailClient.cs
public async Task SendMail(string emailFrom, List<string> emailTo, string subject, string body, bool isPlainText) {
try {
var apiKey = Utils.GetConfigValue("sendgridAPIKey");
var emails = new List<EmailAddress>();
foreach (string email in emailTo) {
emails.Add(new EmailAddress(email));
}
var plainTextContent = "";
var htmlContent = "";
if (!isPlainText) {
htmlContent = body;
} else {
plainTextContent = body;
}
var message = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress(emailFrom, "LobbyCentral"), emails, subject, plainTextContent, htmlContent);
//if (metaData != null)
// message.AddCustomArgs(metaData);
foreach (string filename in FileAttachments) {
if (System.IO.File.Exists(filename)) {
using (var filestream = System.IO.File.OpenRead(filename)) {
await message.AddAttachmentAsync(filename, filestream);
}
}
}
foreach (PlainTextAttachmentM plainTextM in PlainTextAttachments) {
byte[] byteData = Encoding.ASCII.GetBytes(plainTextM.Content);
var attachment = new Attachment();
attachment.Content = Convert.ToBase64String(byteData);
attachment.Filename = plainTextM.AttachmentFilename;
attachment.Type = "txt/plain";
attachment.Disposition = "attachment";
message.AddAttachment(attachment);
}
var client = new SendGridClient(apiKey);
var response = await client.SendEmailAsync(message);
if (response.IsSuccessStatusCode) {
if (DeleteAttachmentsAfterSend && FileAttachments.Count > 0) {
foreach (string filename in FileAttachments) {
if (System.IO.File.Exists(filename)) {
System.IO.File.Delete(filename);
}
}
}
} else {
Utils.DebugPrint("error sending email");
}
} catch (Exception ex) {
throw new Exception(string.Format("{0}.{1}: {2} {3}", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message, ex.StackTrace));
}
}