Code gửi thư bằng gmail

Đăng bởi : 4/08/2014

thuvienwinform - Ứng dụng của nó khá nhiều ví dụ như báo lỗi sản phẩm, liên hệ tác giả, lấy key,...Trong code mình dùng máy chủ smtp của google. Các bạn có thể dùng các máy chủ khác hỗ trợ smtp như OutLook nhưng khi đó địa chỉ máy chủ và cổng sẽ khác, chỉnh lại là OK. Nếu code không hoạt động thì bạn tham khảo cách cài đặt tài khoản Gmail để smtp hoạt động ở bài: http://thuvienwinform.blogspot.com/2014/03/tfs-thiet-lap-email-thong-bao-alert-cho-team-foundation-server-bang-gmail-hoac-live-mail-giup-cap-nhat-cong-viec-kip-thoi.html

Project demo: https://www.dropbox.com/s/ey7fksmiddqjpkm/thuvienwinform-GuiThu.rar (26KB)

Sử dụng 2 thư viện:
+ using System.Net.Mail;
+ using System.Net;
để thực hiện công việc này

Code:
  
private void GuiThu(string diachigui, string matkhau, string diachinhan, string tieude, string noidung)
{
//using System.Net.Mail;
//using System.Net;
    #region Tạo nội dung thư
    MailMessage mail = new MailMessage(diachigui, diachinhan, tieude, noidung);
    #endregion

    #region Cấu hình smtp
    SmtpClient smtp = new SmtpClient()
    {
        //Máy chủ smtp
        Host = "smtp.gmail.com",
        //Cổng gửi thư
        Port = 587,
        //Tài khoản Gmail
        Credentials = new NetworkCredential(diachigui, matkhau),
        EnableSsl = true
    };
    #endregion

    #region Gửi thư
    smtp.Send(mail);
    #endregion
} 


{ 2 comments }

  1. a ơi. a làm thêm dc gửi tập tin bằng giao thức smtp không ?. có hậu tạ ạ !

    ReplyDelete
    Replies
    1. Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
      ContentDisposition disposition = attachment.ContentDisposition;
      disposition.CreationDate = File.GetCreationTime(attachmentFilename);
      disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
      disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
      disposition.FileName = Path.GetFileName(attachmentFilename);
      disposition.Size = new FileInfo(attachmentFilename).Length;
      disposition.DispositionType = DispositionTypeNames.Attachment;
      mail.Attachments.Add(attachment);

      Delete

Nhận ngay 100$ cho VPS

Mua hàng ủng hộ page

Ủng hộ page

Nhãn

Code (45) Team Foundation Server (17) Database (14) News (14) product (13) toolbox (10) Linq (9) SoftDesign (8) XNA (6) API (5) Project (5) item (4)

- Bản quyền thuộc về Thư Viện WinForm - Giao diện: Metrominimalist - Thiết kế: Johanes Djogan -