Error in client.SendAsync

本文关键字:SendAsync client in Error | 更新日期: 2023-09-27 18:16:47

我尝试按照代码发送电子邮件:

http://msdn.microsoft.com/es-es/library/system.net.mail.smtpclient (v = vs.110) . aspx

通过Gmail在。net中发送电子邮件

所以我做了:

SmtpClient client = new SmtpClient("smtp.gmail.com",587);
MailAddress from = new MailAddress("xxx@gmail.com","Jane " + (char)0xD8 + " Clayton",System.Text.Encoding.UTF8);
MailAddress to = new MailAddress("yyy@gmail.com");
MailMessage message = new MailMessage(from, to);
message.Body = "This is a test e-mail message sent by an application. ";
string someArrows = new string(new char[] { ''u2190', ''u2191', ''u2192', ''u2193' });
message.Body += Environment.NewLine + someArrows;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "test message 1" + someArrows;
message.SubjectEncoding = System.Text.Encoding.UTF8;
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
string userState = "test message1";
client.SendAsync(message, userState);
Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
string answer = Console.ReadLine();
if (answer.StartsWith("c") && mailSent == false)
{
    client.SendAsyncCancel();
}
message.Dispose();
Console.WriteLine("Goodbye.");
return View();

但在"client "行出现问题。(消息,是以userState);"错误提示:

System.Net.Mail类型的未处理异常。在System.dll中出现SmtpException',但未在用户代码中处理。

附加信息:Error when sending mail.

我怎么能解决它??

Error in client.SendAsync

Gmail需要SSL连接

设置EnableSsl为true

先将代码放在try catch块内-

.....//other codes
try{
    client.SendAsync(message, userState);
}
catch(Exception e){
    //add a breakpoint here to see what is the error
}

然后,在catch块中添加一个断点,并开始调试以查看错误/异常是什么。通常大多数异常都包含修复它的指令。找到错误,找到解决方法

最后我修改了代码如下>>

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            msg.To.Add("RecipientMail");
            msg.From = new MailAddress("sender@gmail.com", "gmailpassword", System.Text.Encoding.UTF8);
            msg.Subject = "UR SUBJECT";
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.Body = "UR BODY";
            msg.BodyEncoding = System.Text.Encoding.UTF8;
            msg.IsBodyHtml = false;
            //Aquí es donde se hace lo especial
            SmtpClient client = new SmtpClient();
            client.Credentials = new System.Net.NetworkCredential("sender@gmail.com", "gmailpassword");
            client.Port = 587;
            client.Host = "smtp.gmail.com";
            client.EnableSsl = true; //Esto es para que vaya a través de SSL que es obligatorio con GMail
            try
            {
                client.Send(msg);
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }

和设置我的gmail帐户>>https://www.google.com/settings/security/lesssecureapps

谢谢你的帮助!