Send email using smtp server.


We can send email using smtp server to any email address. We are using gmail smtp server to send email. For this we required Google username and password for authentication. If you want to send html text in body message than set IsBodyHtml property of MailMessage to true else false.

using System.Net.Mail;
public bool SendEmail()
{
    bool status = false;
    SmtpClient smtp = null;
    string sFrom = "From Email ID";
    string sTo = "To Email ID";
    string sBody = "Email body text";
    string sSubject = "Email subject";
    string sUser = "From Email ID";
    string sPwd = "From Email password";
    try
    {
        MailMessage mailmessage = new MailMessage();
        mailmessage.From = new MailAddress(sFrom);
        mailmessage.To.Add(sTo);
        mailmessage.Subject = sSubject;
        mailmessage.Body = sBody;
        mailmessage.IsBodyHtml = true; //false if body text is not in html format.
        smtp = new SmtpClient("Smtp.gmail.com");//send email using gmail smtp server.
        smtp.EnableSsl = true;
        smtp.Port = 587;
        smtp.Credentials = new System.Net.NetworkCredential(sUser, sPwd);//Google username and password for authentication.
        smtp.Send(mailmessage);
        status = true;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        smtp.Dispose();
    }
    return status;
}