Tuesday, August 30, 2016

Send email class using SmtpClient in C#

Here's a simple class that sends email using SmtpClient class. The code references System.Net.Mail namespace to access the SmtpClient class and other related assemblies.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Net.Mail;

public class SendEMail
{   
    public void SendMailToClient(string from, string to, string subject,string body)
    {
        try
        {
            MailMessage message = new MailMessage();
            SmtpClient client = new SmtpClient();
            message.From = new MailAddress(from);
            message.To.Add(to);
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = true;
            //client.Host = ConfigurationManager.AppSettings["Host"];
            client.UseDefaultCredentials = false;
            client.Send(message);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void SendMailToClient(string from, string name, string to, string subject, string body)
    {
        try
        {
            MailMessage message = new MailMessage();
            SmtpClient client = new SmtpClient();
            message.From = new MailAddress(from, name);
            message.To.Add(to);
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = true;
            //client.Host = ConfigurationManager.AppSettings["Host"];
            client.UseDefaultCredentials = false;
            client.Send(message);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

0 comments:

Post a Comment