Send Mail using Gmail SMTP in C#

Before using this code you need add following namespace

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

You just copy paste the following code in your program.

public int SendEmail(string sFromEmail, string sHeader, string query)

{

    string sToEmail;

    bool fSSL = true;

    try

    {

        //Creating Message object

 

        System.Web.Mail.MailMessage message = new System.Web.Mail.MailMessage();

        message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com");

        message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");

        message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");

        if (fSSL)

          message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");

          message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");

          message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "[email protected]");

          message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "Password");

 

          //Preparing the message object....

 

         message.From = "[email protected]";

         message.To = sFromEmail;

         message.Subject = sHeader;

         message.BodyFormat = System.Web.Mail.MailFormat.Html;

         string html = @"<html><head><link href='CSS/WebCss/WebCss.css' rel='stylesheet' type='text/css' />

         </head><body >";

         html += "<h1>Welcome to Avinash Aher World</h1><br>"+query;

         html += "</body></html>";

         message.Body = html;

         System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com";

         System.Web.Mail.SmtpMail.Send(message);

         return 1;

    }

    catch (Exception)

    {

         return 0;

    }

} 

Ebook Download
View all
Learn
View all