SMTP 的发送方法总是抛出异常。消息是:发送邮件失败
这是我的代码:
MailMessage mm = new MailMessage();
mm.To.Add("Yuvraj.dhot@xxxxx.co.in");
mm.From = new MailAddress("Kumar.Chaudhari@xxxxx.co.in");
mm.Subject = "Ant Subject";
mm.Body = "Body Cha MEssag here ";
SmtpClient ss = new SmtpClient("localhost");
ss.EnableSsl = false;
try
{
**ss.Send(mm);**
Result.Text = "Message Sent";
Result.ForeColor = System.Drawing.Color.Green;
}
catch (SmtpException ex)
{
Result.Text = "Message Not Sent : \n\n " + ex.Message;
Result.ForeColor = System.Drawing.Color.Red;
}
我也试过用
ss.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
现在它没有抛出任何异常,它执行正常但收件人没有在他的收件箱中收到任何邮件。
我该如何解决这个问题?
编辑 - 这是我得到的堆栈跟踪
Message=Failure sending mail. Source=System StackTrace: at System.Net.Mail.SmtpClient.Send
(MailMessage message) at WebApplication1._Default.Page_Load(Object sender, EventArgs e) in D:\Emcure-
Kumar\Work\Not in Use\WebApplication1\WebApplication1\Default.aspx.cs:line 30 InnerException:
System.Net.WebException Message=Unable to connect to the remote server Source=System StackTrace: –
at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async,
IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) at
System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout,
GeneralAsyncDelegate asyncCallback) at System.Net.PooledStream.Activate(Object owningObject,
GeneralAsyncDelegate asyncCallback) at System.Net.ConnectionPool.GetConnection(Object owningObject,
GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
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)
InnerException: System.Net.Sockets.SocketException Message=No connection could be made because the
target machine actively refused it 127.0.0.1:25 Source=System ErrorCode=10061 NativeErrorCode=10061
请您参考如下方法:
您的执行应该包含比“发送邮件失败”更多的信息
要进行调试,请查看此链接以了解有关 SmtpClient.Send 方法抛出的异常的详细信息 -> SmtpClient.Send Method
此代码适用于“smtp.google.com”
MailMessage mm = new MailMessage();
mm.From = new MailAddress("xx");
mm.To.Add("xx");
mm.Subject = "Ant Subject";
mm.Body = "Body Cha MEssag here ";
SmtpClient ss = new SmtpClient();
ss.Host="smtp.gmail.com";
ss.Port = 587;
ss.EnableSsl = true;
ss.Credentials = new System.Net.NetworkCredential("xx", "xx");
try
{
ss.Send(mm);
Label1.Text = "Message Sent";
Label1.ForeColor = System.Drawing.Color.Green;
}
catch (SmtpException ex)
{
Label1.Text = "Message Not Sent : \n\n " + ex.Message;
Label1.ForeColor = System.Drawing.Color.Red;
}
Google 要求启用 SSL 并将端口 587 作为传出端口。您还需要一个 Google 帐户作为凭据。
您的代码没有问题 - 很可能是您的服务器或防火墙
