使用gmail smtp出现异常时,我遇到了一个问题。
1)允许安全性较低的应用:打开
2)尝试使用端口587、465、25(相同的例外)
3)尝试禁用SSL(相同的例外)
4)smtp.gmail.com的telnet,用于465、587端口,以及从用于smtp的电子邮件地址直接发送
想法?
public async Task SendEmail(string subject, string message)
{
MailAddress fromAddress = new MailAddress("user_from@gmail.com");
MailAddress toAddress = new MailAddress("user_to@gmail.com");
MailMessage mail = new MailMessage(fromAddress.Address, toAddress.Address);
mail.Subject = subject;
mail.Body = message;
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Timeout = 20000;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("user_from@gmail.com", "password");
try
{
client.Send(mail);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
使用端口587的异常:
{System.Net.Mail.SmtpException: The operation has timed out.
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at EmailsUtilities.<SendEmail>d__1.MoveNext() in client.Send(mail);
使用端口465的异常:
{System.Net.Mail.SmtpException: Failure sending mail. --->
System.IO.IOException: Unable to read data from the transport connection: The
connection was closed.
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32
offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader
caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at EmailsUtilities.<SendEmail>d__1.MoveNext() in client.Send(mail);
更新:
将client.Send(mail)
更改为await client.SendMailAsync(mail)
后,获得新的异常:
{System.Net.Mail.SmtpException: Syntax error, command
unrecognized. The server response was:
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at
System.Net.Mail.SmtpConnection.ConnectAndHandshakeAsyncResult.End(IAsyncResult
result)
at System.Net.Mail.SmtpTransport.EndGetConnection(IAsyncResult result)
at System.Net.Mail.SmtpClient.ConnectCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at
System.Runtime.CompilerServices.TaskAwaiter
.HandleNonSuccessAndDebuggerNotificati
on(Task task)
at EmailsUtilities.<SendEmail>d__1.MoveNext() in client.SendMailAsync
System.Net.Mail.SmtpException
感谢您的帮助!
答案 0 :(得分:0)
最后使用Mail.dll(通过NuGet安装)使电子邮件正常工作。示例:
unsigned int from_hex(char hi_bits, char lo_bits)
{
return from_hex(hi_bits) * 16 + from_hex(lo_bits);
}