2013-06-04 35 views
1

我想使用Gmail發送電子郵件,但我得到以下異常發送電子郵件與Gmail主機和端口

套接字操作試圖無法訪問網絡 [2A00:1450:400C:C05: :6D]:465

你有一個想法如何解決呢?

MailMessage msg = new MailMessage(); 
msg.From = new MailAddress("[email protected]"); 
msg.To.Add("[email protected]"); 
msg.Subject = this.txtSubject.Text; 
msg.Body = this.txtBody.Text; 

SmtpClient client = new SmtpClient("smtp.gmail.com"); 
client.Port = 465; 
client.EnableSsl = true; 
client.Send(msg); 
+0

看到這,不同但略有相似http://stackoverflow.com/questions/11717393/a-socket-operation-was-attempted-to-an-不可達網絡在python-httplib。你也使用代理,你如何驗證憑據? – Dave

+0

我正在驗證web.config中的憑據 – theChampion

+0

只是嘗試不使用web.config並將其全部放在C#代碼中,只是爲了確認它沒有任何區別。此外,GMAIL有時需要您登錄到您的電子郵件帳戶,在那裏會出現一個彈出窗口,等待您確認是否要從此位置發送電子郵件。 – Dave

回答

0

地址:

NetworkCredential basicCredential = 
    new NetworkCredential("username", "password"); 

smtpClient.Host = "mail.mydomain.com"; 
smtpClient.UseDefaultCredentials = false; 
smtpClient.Credentials = basicCredential; 

(從How can I make SMTP authenticated in C#通過)

+0

用戶名和密碼應該來自gmail吧? – theChampion

0

試試這個

using System.Net; 

using System.Net.Mail; 

var fromAddress = new MailAddress("[email protected]", "From Name"); 
var toAddress = new MailAddress("[email protected]", "To Name"); 
const string fromPassword = "fromPass"; 
const string subject = "Subject"; 
const string body = "Body"; 

var smtp = new SmtpClient 
     { 
      Host = "smtp.gmail.com", 
      Port = 587, 
      EnableSsl = true, 
      DeliveryMethod = SmtpDeliveryMethod.Network, 
      UseDefaultCredentials = false, 
      Credentials = new NetworkCredential(fromAddress.Address, fromPassword) 
     }; 
    using (var message = new MailMessage(fromAddress, toAddress) 
       { 
        Subject = subject, 
        Body = body 
       }) 
    { 
smtp.Send(message); 
    } 
0

我已經做了這樣的:

有了這些Usings:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Net.Mail; 

,這個按鈕事件

private void sendmail_Click(object sender, EventArgs e) 
    { 
     try 
     { 

      MailMessage mail = new MailMessage(); 
      SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); 

      mail.From = new MailAddress("[email protected]"); 
      mail.To.Add("[email protected]"); 
      mail.Subject = "something"; 
      mail.Body = "text that is in the mail"; 
//for attachements 
      System.Net.Mail.Attachment attachment; 
      attachment = new System.Net.Mail.Attachment(str); 
      mail.Attachments.Add(attachment); 
//end attachement 

      SmtpServer.Port = 587; 
      SmtpServer.Credentials = new System.Net.NetworkCredential"username from gmail", "password from gmail"); 
      SmtpServer.EnableSsl = true; 

      SmtpServer.Send(mail); 
      MessageBox.Show("Mail Send"); 
      this.Close(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    }