2016-09-24 50 views
-5
void sendMail(string invoiceNumber) 
{ 
    try 
    { 
     MailMessage mail = new MailMessage(); 
     SmtpClient SmtpServer = new SmtpClient("Smtp.gmail.com"); 
     mail.From = new MailAddress("*******@gmail.com"); 
     mail.To.Add("******@gmail.com"); 
     mail.Subject = "Test Mail - 1"; 
     mail.Body = invoiceNumber; 
     mail.Subject = "PDFs Attached"; 
     DirectoryInfo di = new DirectoryInfo(@"C:\Users\User\Desktop\test\"); 
     foreach (var file in di.GetFileSystemInfos("*.pdf*")) 
      mail.Attachments.Add(new Attachment(file.FullName)); 
     SmtpServer.Port = 587; 
     SmtpServer.Credentials = new System.Net.NetworkCredential("*******@gmail.com", "*********"); 
     SmtpServer.EnableSsl = true; 
     SmtpServer.Send(mail); 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.ToString()); 
    } 
} 
+3

請參見[問]和[完美的問題(HTTP:// codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/)。 – rene

+0

歡迎來到SO。你應該閱讀我們如何寫出一個正確的問題。雷內已經提到的鏈接是一個非常好的開始。這次,我編寫了你的​​代碼。但是,這不是一個問題。這只是一個代碼,它包含一個'郵件不發送'的代碼。你必須描述出了什麼問題?到目前爲止,你的發現是什麼? – Christos

+0

[通過Gmail在.NET中發送電子郵件]的可能副本(http://stackoverflow.com/questions/32260/sending-email-in-net-through-gmail) – Igor

回答

0

https://www.google.com/settings/security/lesssecureapps使用此鏈接允許您的Gmail ID的安全性較低的應用程序....

void sendMail(string invoiceNumber) 
{ 
    try 
    { 
     MailMessage mail = new MailMessage(); 
      mail.To.Add("recevermailid"); 
      mail.From = new MailAddress("sender id"); 
      mail.Subject = "Confirmation"; 
      string Body = "your message body"; 
      mail.Body = Body; 
      mail.IsBodyHtml = true; 
      SmtpClient smtp = new SmtpClient(); 
      smtp.Host = "smtp.gmail.com"; 
      smtp.Port = 587; 
      smtp.UseDefaultCredentials = false; 
      smtp.Credentials = new System.Net.NetworkCredential 
      ("sender email", "seneder email password");// Enter seders User name and password 
      smtp.EnableSsl = true; 
      smtp.Send(mail); 

    catch (Exception ex) 
    { 
     Console.WriteLine(ex.ToString()); 
    } 
}