2013-02-08 33 views
0

我有以下的代碼是不工作:如何在.net中使用SmtpClient發送郵件?

public static void SendMail(string content, string title, List<string> address) 
{ 
    SmtpClient client = new SmtpClient(Server,Port); 
    client.Port = Port; 
    client.Host = Server; 
    client.EnableSsl = false; 
    client.Timeout = 10000; 
    client.DeliveryMethod = SmtpDeliveryMethod.Network; 
    client.UseDefaultCredentials = false; 
    client.Credentials = new System.Net.NetworkCredential(Username, Password); 

    foreach(string to in address) 
    { 
     MailMessage mm = new MailMessage(From, to, title, content); 
     mm.BodyEncoding = UTF8Encoding.UTF8; 
     mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; 

     client.Send(mm); 
    } 
    client.Dispose(); 
} 

我收到以下錯誤:

Mailbox unavailable. The server response was: You must give your username and password to send mail through this service

你可以看到,我傳遞一個用戶名和密碼。爲什麼我仍然遇到這個問題?

+0

這是針對每個SMTP服務器。您需要爲自己的互聯網服務提供商檢查SMTP的設置。 – 2013-02-08 17:17:56

+0

您使用哪種電子郵件服務? – Arran 2013-02-08 17:29:01

回答

2

這裏我使用例如使用Gmail服務器

MailMessage mail = new MailMessage(); 
     mail.To.Add(textBox1.Text); 

     mail.From = new MailAddress("Yourgmailid"); 
     mail.Subject = "Email using Gmail"; 

     string Body = "Hi, this mail is to test sending mail" + 
         "using Gmail in ASP.NET"; 
     mail.Body = Body; 

     mail.IsBodyHtml = true; 
     SmtpClient smtp = new SmtpClient(); 
     smtp.Host = "smtp.gmail.com"; 
     smtp.Credentials = new System.Net.NetworkCredential 
      ("Yourgmailid, "Password"); 

     smtp.EnableSsl = true; 
     smtp.Send(mail); 
相關問題