我开发了两种方法:分别使用SmtpClient.Send和SmtpClient.SendMailAsync的SendEmailBySmtp()和SendEmailAsyncBySmtp()。
当前第一种方法有效,但第二种无效。没有错误,但是没有电子邮件。
我该如何解决?
class Program
{
static void Main(string[] args)
{
SendEmailBySmtp();
SendEmailAsyncBySmtp();
}
static void SendEmailBySmtp()
{
MailMessage message = new MailMessage()
{
From = new MailAddress("test@example.com", "Test User"),
Subject = "Subject",
Body = "Body"
};
message.To.Add("test@example.com");
message.CC.Add("test@example.com");
message.BodyEncoding = UTF8Encoding.UTF8;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
using (SmtpClient client = new SmtpClient())
{
client.Port = 587;
client.Host = "smtp.office365.com";
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("test@example.com", "password");
client.Send(message);
}
}
static async Task SendEmailAsyncBySmtp()
{
MailMessage message = new MailMessage()
{
From = new MailAddress("test@example.com", "Test User"),
Subject = "Subject",
Body = "Body"
};
message.To.Add("test@example.com");
message.CC.Add("test@example.com");
message.BodyEncoding = UTF8Encoding.UTF8;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
using (SmtpClient client = new SmtpClient())
{
client.Port = 587;
client.Host = "smtp.office365.com";
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("test@example.com", "password");
await client.SendMailAsync(message);
}
}
}
答案 0 :(得分:3)
问题出在select
方法中,您忘记等待第二个调用。因为在主要方法中不能使用await关键字,所以必须手动“等待”线程
只需执行以下操作:
<div data-bind="with: SelectedItem">
<select id="select" data-bind="options: $root.OptionsList, optionsText: 'description', optionsValue: 'opt_id', optionsCaption: 'Select', value: $root.selectedOption"></select>
</div>
您的问题的答案是:该程序在Main
执行该工作之前结束,因此电子邮件发送操作在发送之前已停止。