我正在尝试发送一封电子邮件(代码取自Microsoft文档),但操作被取消并且邮件没有收到邮件。帮助解决问题。
static bool mailSent = false;
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
String token = (string)e.UserState;
if (e.Cancelled)
{
Console.WriteLine("[{0}] Send canceled.", token);
}
if (e.Error != null)
{
Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
}
else
{
Console.WriteLine("Message sent.");
}
mailSent = true;
}
public static void SendMessage()
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 465;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(mailFrom, password);
MailAddress from = new MailAddress(mailFrom,"saturn",System.Text.Encoding.UTF8);
MailAddress to = new MailAddress(mailTo);
MailMessage message = new MailMessage(from, to);
message.Body = "This is a test e-mail message sent by an application. ";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "test message 1";
message.SubjectEncoding = System.Text.Encoding.UTF8;
client.SendCompleted += new
SendCompletedEventHandler(SendCompletedCallback);
string userState = "test message1";
client.SendAsync(message, userState);
if (mailSent == false)
{
client.SendAsyncCancel();
}
message.Dispose();
}
当然,您从 Microsoft 那里获取了代码,但在检查之间扔掉了关键线
client.SendAsync
:字符串答案 = Console.ReadLine();
并相应地简化了检查。但是调用了的代码
client.SendAsync
不会等待任何东西,而是继续前进并进入你的if
,因为此时处理程序SendCompletedCallback
尚未执行。您可以进行同步调用
或者异步执行
同时,添加
async
到函数定义中也不错