使用gmail和.net

时间:2015-08-19 10:33:45

标签: c# asp.net email

获得例外:

  

发送邮件失败。

使用System.Net.Mail.Smtp时 在smtp.Send(message);

行的C#.NET中
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();            
message.To.Add(sendto);    
message.Subject = "CP1 Lab Password";
message.From = new System.Net.Mail.MailAddress("abc@gmail.com");
message.Body = mail_message;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("yoursmtphost");

smtp.Host = "smtp.gmail.com";
smtp.Port = 465; //(465 for SSL)587 
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("abc@gmail.com", "mypassword");    
smtp.Send(message);

修改1:

以下是错误的详细信息:

  

连接尝试失败,因为连接方没有   在一段时间后正确回应,或建立连接   失败,因为连接的主机无法响应......

使用端口25时出现相同的错误。

此代码过去几个月才起作用,但今天它无效

1 个答案:

答案 0 :(得分:0)

从您的异常消息(不完整)和代码开始,很难说出您的情况出了什么问题。未找到服务器时,抛出发送邮件失败,端口无法连接。这意味着直到现在才建立连接。

如果建立连接但未正确执行身份验证,则会引发异常消息:“SMTP服务器需要经过身份验证的连接...”。我建议您检查PORT,SMTP服务器主机(不要添加http://),然后重试。 SMTP连接(在大多数情况下)需要

  1. SMTP服务器主机:smtp.gmail.com就够了!
  2. 要连接的端口:我一直使用SMTP的默认TCP端口,25。它可以工作。
  3. EnableSsl:大多数都需要它。我建议你一直使用它。 client.EnableSsl = true;
  4. 所有人都需要凭证:没有服务器允许机器人发送电子邮件。在此问题中,如果您创建一个新帐户。您可能会遇到以编程方式发送电子邮件的问题,我遇到了新帐户没有发送电子邮件的问题,而旧帐户(我的默认帐户)正在发送电子邮件没有任何问题。
  5. 以下代码模板(如果填充了准确的参数)肯定会发送电子邮件,因为我已经测试并验证了数十亿次。 :)

    // You should use a using statement
    using (SmtpClient client = new SmtpClient("<smtp-server-address>", 25))
    {
       // Configure the client
       client.EnableSsl = true;
       client.Credentials = new NetworkCredential("<username>", "<password>");
       // client.UseDefaultCredentials = true;
    
       // A client has been created, now you need to create a MailMessage object
       MailMessage message = new MailMessage(
                                "from@example.com", // From field
                                "to@example.com", // Recipient field
                                "Hello", // Subject of the email message
                                "World!" // Email message body
                             );
    
       // Send the message
       client.Send(message);
    
       /* 
        * Since I was using Console app, that is why I am able to use the Console
        * object, your framework would have different ones. 
        * There is actually no need for these following lines, you can ignore them
        * if you want to. SMTP protocol would still send the email of yours. */
    
       // Print a notification message
       Console.WriteLine("Email has been sent.");
       // Just for the sake of pausing the application
       Console.Read();
    }
    

    发送电子邮件有时会令人头疼,因为它还需要对网络有一些基本的了解。我写过一篇文章,内容涉及在.NET框架中发送电子邮件以及初学者通常偶然发现的一些问题。您可能也有兴趣阅读该文章。 http://www.codeproject.com/Articles/873250/Sending-emails-over-NET-framework-and-general-prob

相关问题