2008-11-18 57 views

Trả lời

125
using System.Net; 
using System.Net.Mail; 


SmtpClient smtpClient = new SmtpClient(); 
NetworkCredential basicCredential = 
    new NetworkCredential("username", "password"); 
MailMessage message = new MailMessage(); 
MailAddress fromAddress = new MailAddress("[email protected]"); 

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

message.From = fromAddress; 
message.Subject = "your subject"; 
//Set IsBodyHtml to true means you can send HTML email. 
message.IsBodyHtml = true; 
message.Body = "<h1>your message body</h1>"; 
message.To.Add("[email protected]"); 

try 
{ 
    smtpClient.Send(message); 
} 
catch(Exception ex) 
{ 
    //Error, could not send the message 
    Response.Write(ex.Message); 
} 

Bạn có thể sử dụng mã ở trên.

+0

tên người dùng và mật khẩu đến từ đâu? và mail.mydomain.com là gì? là tên DNS của anh ta? – Shyju

+5

là địa chỉ email và mật khẩu của bạn, mail.mydomain.com là máy chủ SMTP của bạn (ví dụ: smtp.gmail.com). – Arief

+0

Bạn nên bọc đối tượng MailMessage trong một câu lệnh sử dụng (hoặc gọi Dispose vào nó sau khi bạn đã hoàn thành), phải không? – Ben

1

Làm thế nào để bạn gửi tin nhắn?

Các lớp trong không gian tên System.Net.Mail (có lẽ là những gì bạn nên sử dụng) có hỗ trợ đầy đủ để xác thực, được chỉ định trong Web.config hoặc sử dụng thuộc tính SmtpClient.Credentials.

63

Đảm bảo bạn đặt SmtpClient.Credentialssau gọi SmtpClient.UseDefaultCredentials = false.

Thứ tự quan trọng khi đặt SmtpClient.UseDefaultCredentials = false sẽ đặt lại SmtpClient.Credentials thành không.

+8

Nếu tôi có thể upvote này một vài lần nữa, tôi sẽ. – Joshua

+1

Omg Tôi đã mất rất nhiều thời gian trước khi tôi nhìn thấy câu trả lời này !! Cảm ơn bạn 1! – avidenic

+2

đây là cũ, nhưng vàng; damn nó đã giúp – MihaiC

1

Để gửi thư qua TLS/SSL, bạn cần đặt Ssl của lớp SmtpClient thành true.

string to = "[email protected]"; 
string from = "[email protected]"; 
MailMessage message = new MailMessage(from, to); 
message.Subject = "Using the new SMTP client."; 
message.Body = @"Using this new feature, you can send an e-mail message from an application very easily."; 
SmtpClient client = new SmtpClient(server); 
// Credentials are necessary if the server requires the client 
// to authenticate before it will send e-mail on the client's behalf. 
client.UseDefaultCredentials = true; 
client.EnableSsl = true; 
client.Send(message); 
+0

viết một số ví dụ mã về SSL vs SMTP Client để tạo câu trả lời tốt hơn –

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