Thay vì chúng ta gởi mail từ website nhà cung cấp hay từ gmail hay từ outlook, chúng ta có thể hoàn toàn gởi mail tự động bằng code C#.
try
{
// Cấu hình thông tin email
string fromAddress = "xxx@gmail.com"; // Địa chỉ email của bạn
string toAddress = "yyyy@gmail.com"; // Địa chỉ email người nhận
string subject = "Tiêu đề email";
string body = "Nội dung email";
// Tạo đối tượng MailMessage
MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromAddress);
mail.To.Add(toAddress);
mail.Subject = subject;
mail.Body = body;
// Cấu hình SMTP
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new NetworkCredential(fromAddress, "pass app gmail"); // Dùng mật khẩu ứng dụng
smtp.EnableSsl = true; // Bật SSL để bảo mật
// Phương thức gởi mail
smtp.Send(mail);
Label1.Text = "Đã gởi mail thành công !";
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
Muốn đính kèm file:
foreach (string f in arr)
{
System.Net.Mail.Attachment attachment_i = new Attachment(f);
mail.Attachments.Add(attachment_i);
}
Code C# gởi mail được ứng dụng trong việc tự động gởi mail cho khách hàng theo định kỳ.
Ứng dụng gởi nhiều mail cùng 1 lúc.
Ứng dụng gởi mail theo mẫu chi định.
Lỗi gởi mail 01:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required. Learn more at
Gởi mail với winform C#