.NET为什么我不能发送电子邮件?

时间:2010-10-11 16:46:09

标签: .net email

这是我的代码:

try
{
    MailMessage m = new MailMessage
        ("testesmtpmic@gmail.com",
         "toMyEmail@gmail.com",
         "Quarterly data report.",
         "Hello, world.");

    SmtpClient client = new SmtpClient("smtp.gmail.com", 465);
    client.Credentials = new NetworkCredential("testesmtpmic@gmail.com", "password");
    client.EnableSsl = true;
    client.Send(m);
    Console.WriteLine("sent");
}
catch (InvalidOperationException ey)
{
    Console.WriteLine(ey.Message);
}
catch (SmtpFailedRecipientException sm)
{
    Console.WriteLine(sm.Message);
}
catch (SmtpException ex)
{
    Console.WriteLine(ex.Message);
}

此代码在SmtpException处产生此错误: “邮件发送失败。” 完整的例外是:

ex.ToString()   "System.Net.Mail.SmtpException: Failure sending mail. 
  ---> System.Net.WebException: Unable to connect to the remote server 
  ---> System.Net.Sockets.SocketException: A connection attempt failed because 
    the connected party did not properly respond after a period of time, or 
    established connection failed because connected host has failed to respond 
    74.125.67.109:587
  at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
  at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
  --- End of inner exception stack trace ---
  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)\r\n   at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
  at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
  at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
  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 ConsoleApplication3.Program.Main(String[] args) in c:\\users\\alan\\documents\\visual studio 2010\\Projects\\ConsoleApplication3\\ConsoleApplication3\\Program.cs:line 24" string

3 个答案:

答案 0 :(得分:0)

尝试使用此代码段发送简单的电子邮件:

var smtpClient = new SmtpClient("smtp.gmail.com", 587)
{
    Credentials = new NetworkCredential(
        "yourusername@gmail.com", 
        "yourpassword"
    ),
    EnableSsl = true
};
smtpClient.Send("from@gmail.com", "to@gmail.com", "subject", "body");

与您的代码的不同之处在于端口587(而不是您的465)。

答案 1 :(得分:0)

您的脚本似乎无法与指定端口上的Gmail服务器联系。确保您的服务器可以通过远程登录到达该地址/端口并查看是否收到回复。

答案 2 :(得分:0)

一段时间发生了类似的情况。我按照我在线发现的模板在System.Net中使用SmtpClient。在研究之后,我发现我的ISP制定了一些策略来删除某些端口上的邮件流量,因为他们希望人们通过他们自己的邮件服务器路由流量(打击垃圾邮件)。

我的情况很复杂,因为我需要使用的端口(用于我的业务ymail帐户)被我的ISP阻止。原来我唯一能连接的邮件服务器是gmail。因此,您可以尝试使用不同的邮件提供商,或者与您的ISP讨论邮件丢弃/阻止策略以及如何处理某些端口。

这对我有用:

private bool sendEmailAlert(string emailAddress, string subject, string message)
        {
            try
            {
                //Construct e-mail message:
                string fromAddress = "you@somedomain.com",
                       fromName = "Your Biz";//"Don't Reply";
                MailMessage email_msg = new MailMessage();
                email_msg.From = new MailAddress(fromAddress, fromName);
                email_msg.Sender = new MailAddress(fromAddress, fromName);
                email_msg.To.Add(emailAddress);
                email_msg.Subject = subject;
                email_msg.Body = message;
                SmtpClient mail_client = new SmtpClient();
                NetworkCredential network_cdr = new NetworkCredential();
                network_cdr.UserName = "you@somedomain.com";
                network_cdr.Password = "password";
                mail_client.Credentials = network_cdr;
                mail_client.Port = 587;
                mail_client.Host = "smtp.gmail.com";
                mail_client.EnableSsl = true;

                //Send e-mail message;
                mail_client.Send(email_msg);
                return true;
            }
            catch (Exception ex)
            {
                StreamWriter errorFile = new StreamWriter("errorLog.txt", true);
                errorFile.WriteLine(DateTime.Now.ToString() + ": sendEmailAlert exception: " + ex.ToString());
                errorFile.Close();
                return false;
            }
        }