Saturday , 20 April 2024
HOT

Gửi mail trong asp.net sử dụng smtp localhost và gmail

Việc gửi mail là 1 công việc thường ngày và viết ra 1 chương trình gửi mail thật đơn giản nhưng không phải ai cũng biết. Mình xin giới thiệu với các bạn class Email này. Class gửi mail dưới đây hỗ trợ gửi mail thông qua SMTP của localhost và gmail


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

/// <summary>
/// Summary description for ccMailClass
/// </summary>
public class ccMailClass
{  

    public static bool sendMail_UseLocal(string strFrom, string strTo, string strSubject, string strBody)
    {
        MailMessage ms = new MailMessage(strFrom, strTo, strSubject, strBody);
        ms.BodyEncoding = System.Text.Encoding.UTF8;
        ms.SubjectEncoding = System.Text.Encoding.UTF8;
        ms.IsBodyHtml = true;
        ms.ReplyTo = new MailAddress(strFrom);
        ms.Sender = new MailAddress(strFrom);

        SmtpClient SmtpMail = new SmtpClient();
        SmtpMail.Host = "localhost";

        try
        {
            SmtpMail.Send(ms);
            return true;
        }
        catch
        {
            return false;
        }
    }

    public static bool sendMail_UseGmail(string strFrom,string strPass, string strTo, string strSubject, string strBody)
    {       
        MailMessage ms = new MailMessage(strFrom, strTo, strSubject, strBody);
        
        ms.BodyEncoding = System.Text.Encoding.UTF8;
        ms.SubjectEncoding = System.Text.Encoding.UTF8;
        ms.IsBodyHtml = true;

        ms.ReplyTo = new MailAddress(strFrom);
        ms.Sender = new MailAddress(strFrom);       
                
        SmtpClient SmtpMail = new SmtpClient("smtp.gmail.com", 587);
        SmtpMail.Credentials = new NetworkCredential(strFrom, strPass);
        SmtpMail.EnableSsl = true;

        try
        {
            SmtpMail.Send(ms);
            return true;
        }
        catch
        {
            return false;
        }
        

    }
}


Các bạn có thể download sourcecode tại đây: MailClass

Chúc các bạn thành công

Nguồn: http://chiencong.com

Leave a Reply

Your email address will not be published. Required fields are marked *

*