Saturday 30 April 2011

How To Send An EMail From ASP.NET Web Page.

In Web.Config:

<appSettings>
    <add key="ContactEmailTo" value="Id To Which You Have to Send Mail"/>
    <add key="ContactEmailFrom" value="Id From Which You Have to Send Mail"/>
    <add key="ContactEmailPassword" value="Password of Id From Which You Have to Send Mail"/>
  </appSettings>

In .CS File:

Create Mail Format-
StringBuilder sbMail = new StringBuilder();
sbMail.Append("<table width='70%'><tr><td>EmpId:<b> " + 1000  + "</b></td></tr>");
sbMail.Append("<tr><td>Emp Name:<b> " + Ankur + "</b></td></tr><tr><td></td></tr>");





if (SendEmail(ConfigurationManager.AppSettings["ContactEmailFrom"],
ConfigurationManager.AppSettings["ContactEmailPassword"], ConfigurationManager.AppSettings["ContactEmailTo"],"Subject Of Mail", sbMail.ToString(), System.Web.Mail.MailFormat.Html, "") == true)
{

 }





public static bool SendEmail(string pGmailEmail,string pGmailPassword,string pTo,string pSubject,string pBody,System.Web.Mail.MailFormat pFormat,string pAttachmentPath)
    {
        try
        {
            System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserver",
                              "smtp.gmail.com");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
                              "465");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/sendusing",
                              "2");
           
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            //Use 0 for anonymous
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendusername",
                pGmailEmail);
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendpassword",
                 pGmailPassword);
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
                 "true");
            myMail.From = pGmailEmail;
            myMail.To = pTo;
            myMail.Subject = pSubject;
            myMail.BodyFormat = pFormat;
            myMail.Body = pBody;
           

            System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
            System.Web.Mail.SmtpMail.Send(myMail);
            return true;
        }
        catch (Exception ex)
        {
            throw;
        }
    }

No comments:

Post a Comment