2011-01-13 80 views
46

Tôi muốn gửi email qua máy chủ gmail. Tôi đã đặt đoạn mã sau nhưng nó bị kẹt trong khi gửi. Bất kỳ ý tưởng nào vui lòng ....Gửi email bằng System.Net.Mail qua gmail

MailMessage mail = new MailMessage(); 

     mail.From = new System.Net.Mail.MailAddress("[email protected]"); 

     //create instance of smtpclient 
     SmtpClient smtp = new SmtpClient(); 
     smtp.Port = 465; 
     smtp.UseDefaultCredentials = true; 

     smtp.Host = "smtp.gmail.com";    

     smtp.EnableSsl = true; 

     //recipient address 
     mail.To.Add(new MailAddress("[email protected]")); 

     //Formatted mail body 
     mail.IsBodyHtml = true; 
     string st = "Test"; 

     mail.Body = st; 
     smtp.Send(mail); 

xxxx.com là miền thư trong ứng dụng Google. Cảm ơn ...

+3

Bạn không cần phải nhập mật khẩu của mình ở đâu đó cho máy chủ SMTP? – Mehrdad

+1

Có, máy chủ SMTP của Gmail yêu cầu xác thực. [Link] (http://mail.google.com/support/bin/answer.py?hl=vi&answer=13287) –

+1

Những gì Lambert nói. Thông tin đăng nhập mặc định là Windows có liên quan. Bạn sẽ cần phải chỉ định chúng cho GMail. – leppie

Trả lời

70
MailMessage mail = new MailMessage(); 
mail.From = new System.Net.Mail.MailAddress("[email protected]"); 

// The important part -- configuring the SMTP client 
SmtpClient smtp = new SmtpClient(); 
smtp.Port = 587; // [1] You can try with 465 also, I always used 587 and got success 
smtp.EnableSsl = true; 
smtp.DeliveryMethod = SmtpDeliveryMethod.Network; // [2] Added this 
smtp.UseDefaultCredentials = false; // [3] Changed this 
smtp.Credentials = new NetworkCredential(mail.From, "password_here"); // [4] Added this. Note, first parameter is NOT string. 
smtp.Host = "smtp.gmail.com";    

//recipient address 
mail.To.Add(new MailAddress("[email protected]")); 

//Formatted mail body 
mail.IsBodyHtml = true; 
string st = "Test"; 

mail.Body = st; 
smtp.Send(mail); 
+0

Cảm ơn Sarwar ... Dự đoán của bạn với cổng là chính xác. Tôi sẽ upvote này vào ngày mai. – JCTLK

+2

Một vài quan sát: 1. Đó là "smtp.gmail.com", không phải "smtp.google.com". Tôi đã nhìn chằm chằm vào mã của tôi trong nửa giờ cho đến khi tôi nhận ra tôi đã sử dụng sau này. 2.Cổng 587 dường như hoạt động tốt hơn rất nhiều so với 465 mặc dù mọi thứ khác tôi đã đọc về chủ đề nói để sử dụng cổng 465. 3. Nếu bạn đang sử dụng xác minh hai bước và bạn nên (xem http://www.codinghorror.com/blog/2012/04/make-your-email-hacker-proof.html) bạn phải tạo mật khẩu mới cho ứng dụng của mình. –

+1

FYI, khi tôi chạy vào điều này: Đóng đối tượng SmtpClient của bạn trong mệnh đề 'using'. Bạn phải làm điều này đặc biệt nếu bạn định sử dụng máy khách trong một vòng lặp. – Kyle

7

Đặt smtp.UseDefaultCredentials = false và sử dụng smtp.Credentials = new NetworkCredential (gMailAccount, password);

+0

Tôi cũng đã sử dụng câu trả lời này. Nhưng câu trả lời của Sarwar đã giải quyết xong vấn đề của tôi. Cảm ơn rất nhiều và tôi sẽ upvote này vào ngày mai. Chúc mừng. – JCTLK

11

Tôi đã thử mã C# ở trên để gửi thư từ Gmail đến ID công ty của tôi. Trong khi thực thi ứng dụng, điều khiển đã dừng vô thời hạn tại tuyên bố smtp.Send(mail);

Trong khi Googling, tôi đã xem qua một số code tương tự, đã hoạt động đối với tôi. Tôi đăng mã đó ở đây.

class GMail 
{ 
    public void SendMail() 
    { 
     string pGmailEmail = "[email protected]"; 
     string pGmailPassword = "GmailPassword"; 
     string pTo = "ToAddress"; //[email protected] 
     string pSubject = "Test From Gmail"; 
     string pBody = "Body"; //Body 
     MailFormat pFormat = MailFormat.Text; //Text Message 
     string pAttachmentPath = string.Empty; //No Attachments 

     System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage(); 
     myMail.Fields.Add 
      ("http://schemas.microsoft.com/cdo/configuration/smtpserver", 
          "smtp.gmail.com"); 
     myMail.Fields.Add 
      ("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 
          "465"); 
     myMail.Fields.Add 
      ("http://schemas.microsoft.com/cdo/configuration/sendusing", 
          "2"); 
     //sendusing: cdoSendUsingPort, value 2, for sending the message using 
     //the network. 

     //smtpauthenticate: Specifies the mechanism used when authenticating 
     //to an SMTP 
     //service over the network. Possible values are: 
     //- cdoAnonymous, value 0. Do not authenticate. 
     //- cdoBasic, value 1. Use basic clear-text authentication. 
     //When using this option you have to provide the user name and password 
     //through the sendusername and sendpassword fields. 
     //- cdoNTLM, value 2. The current process security context is used to 
     // authenticate with the service. 
     myMail.Fields.Add 
     ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); 
     //Use 0 for anonymous 
     myMail.Fields.Add 
     ("http://schemas.microsoft.com/cdo/configuration/sendusername", 
      pGmailEmail); 
     myMail.Fields.Add 
     ("http://schemas.microsoft.com/cdo/configuration/sendpassword", 
      pGmailPassword); 
     myMail.Fields.Add 
     ("http://schemas.microsoft.com/cdo/configuration/smtpusessl", 
      "true"); 
     myMail.From = pGmailEmail; 
     myMail.To = pTo; 
     myMail.Subject = pSubject; 
     myMail.BodyFormat = pFormat; 
     myMail.Body = pBody; 
     if (pAttachmentPath.Trim() != "") 
     { 
      MailAttachment MyAttachment = 
        new MailAttachment(pAttachmentPath); 
      myMail.Attachments.Add(MyAttachment); 
      myMail.Priority = System.Web.Mail.MailPriority.High; 
     } 

     SmtpMail.SmtpServer = "smtp.gmail.com:465"; 
     SmtpMail.Send(myMail); 
    } 
} 
+0

hoạt động tốt cho tôi , nơi các giải pháp khác không thành công ... –

+0

Các trường là cần thiết? – Kiquenet

0

Sử dụng Cảng số 587

Với đoạn mã sau, nó sẽ làm việc thành công.

MailMessage mail = new MailMessage(); 
mail.From = new MailAddress("[email protected]", "Enquiry"); 
mail.To.Add("[email protected]"); 
mail.IsBodyHtml = true; 
mail.Subject = "Registration"; 
mail.Body = "Some Text"; 
mail.Priority = MailPriority.High; 

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); 
//smtp.UseDefaultCredentials = true; 
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "<my gmail pwd>"); 
smtp.EnableSsl = true; 
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network; 

smtp.Send(mail); 

Nhưng, có vấn đề với việc sử dụng gmail. Email sẽ được gửi thành công, nhưng hộp thư người nhận sẽ có địa chỉ gmail trong 'từ địa chỉ' thay vì 'từ địa chỉ' được đề cập trong mã.

Để giải quyết vấn đề này, vui lòng thực hiện theo các bước được đề cập tại liên kết sau.

http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html

trước khi làm theo tất cả các bước trên, bạn cần phải xác thực tài khoản gmail của bạn để cho phép truy cập vào các ứng dụng của bạn và cũng là thiết bị. Vui lòng kiểm tra tất cả các bước để xác thực tài khoản tại liên kết sau:

http://karmic-development.blogspot.in/2013/11/allow-account-access-while-sending.html

0
ActiveUp.Net.Mail.SmtpMessage smtpmsg = new ActiveUp.Net.Mail.SmtpMessage(); 
    smtpmsg.From.Email = "[email protected]"; 
    smtpmsg.To.Add(To); 
    smtpmsg.Bcc.Add("[email protected]"); 
    smtpmsg.Subject = Subject; 
    smtpmsg.BodyText.Text = Body; 

    smtpmsg.Send("mail.test.com", "[email protected]", "[email protected]", ActiveUp.Net.Mail.SaslMechanism.Login); 
+1

Một số từ về giải pháp của bạn sẽ tốt đẹp. –

1

này đã làm việc cho tôi:

 MailMessage message = new MailMessage("[email protected]", toemail, subjectEmail, comments); 
     message.IsBodyHtml = true; 

     try { 
      SmtpClient client = new SmtpClient("smtp.gmail.com", 587); 
      client.Timeout = 2000; 
      client.EnableSsl = true; 
      client.DeliveryMethod = SmtpDeliveryMethod.Network; 
      //client.Credentials = CredentialCache.DefaultNetworkCredentials; 
      client.UseDefaultCredentials = false; 
      client.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassord"); 
      client.Send(message); 

      message.Dispose(); 
      client.Dispose(); 
     } 
     catch (Exception ex) { 
      Debug.WriteLine(ex.Message); 
     } 

NHƯNG (tính đến thời điểm viết bài này - Tháng 2017)

Bạn cần ENABLE "Cho phép ứng dụng kém an toàn" bên trong tùy chọn "ứng dụng có quyền truy cập tài khoản" tại " Tài khoản của tôi "cài đặt bảo mật/bảo mật của google (https://myaccount.google.com)

Các vấn đề liên quan