30/10/2016

Sử dụng C# gửi email bằng gmail

Đôi khi bạn cần gửi email từ ứng dụng của bạn và... bạn chọn gmail để thực hiện việc gửi email giúp bạn, việc này dễ khi dùng với c#

 private bool SendEmail(string subject, string htmlString)

{

try

{

MailMessage message = new MailMessage();

SmtpClient smtp = new SmtpClient();

message.From = new MailAddress("your_out_going_address");

message.To.Add(new MailAddress("receive_address"));

message.Subject = subject;

message.IsBodyHtml = true; //to make message body as html  

message.Body = htmlString;

smtp.Port = 587;

smtp.Host = "smtp.gmail.com"; //for gmail host  "smtp.gmail.com"

smtp.EnableSsl = true;

smtp.UseDefaultCredentials = false;

smtp.Credentials = new NetworkCredential("your_out_going_address", "your_out_going_address_password");

smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

smtp.Send(message);

return true;

}

catch (Exception ex) {

//Your common write log method

//LogError(GetExceptionMsg(ex));

return false;

}

}

//Lưu ý:

// tìm google "Less secure app access" và tắt theo hướng dẫn.....

Không có nhận xét nào:

Đăng nhận xét