SIGN UP MEMBER LOGIN:    
ARTICLE

ASP.NET Send email using GMAIL

Posted by Bryian Tan Articles | ASP.NET Programming December 03, 2010
In this article you will learn how to use ASP.NET - Code snippet to send email using GMAIL.
Reader Level:

Introduction

Several days ago someone in the forum has asked "how to send email using GMAIL". I have the code in my computer but it took me a while to locate it and put it in certain format. So, I decided to post this code snippet on the web so that I can access it anytime and share it with other user. Shown below is the code.  

If you decide to store the mail server information in the web.config file, refer to listing 1.

Listing 1 

    <system.web>
      <system.net>

        <mailSettings>
          <smtp from="YourGMAIL ">

            <network host="smtp.gmail.com" defaultCredentials="false"
            port="587" userName ="YourGMAIL" password="YourGmailPassword" />
          </smtp>
        </mailSettings>
      </system.net>
    </system.web>


Shown in listing 2 is the code snippet to send email. 

Listing 2 

    public string SendEmail(bool readWebConfig)
    {
        string emailStatus = string.Empty;

        string from = "YourGmail"; //Replace this with your own correct Gmail Address

        string to = "someone@hotmail.com"

        string cc = "someone@yahoo.com; someone2@gmail.com; someone3@yahoo.com";

        string bcc = "";

        string fromName = "bryian";

        string userName = "YourGMAIL";

        string password = "YourGMAILPassword";

        Attachment attachment = null;

        //if you want to send attachment, include the file location
       // Attachment attachment = new Attachment("file location");

        SmtpClient client = new SmtpClient();
        client.EnableSsl = true; //Gmail works on Server Secured Layer

        if (!readWebConfig)
        {
            client.Credentials = new System.Net.NetworkCredential(userName, password);
            client.Port = 587; // Gmail works on this port
            client.Host = "smtp.gmail.com"; //hotmail: smtp.live.com
        }

        try
        {
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(from, fromName);
                mail.ReplyTo = new MailAddress(from, fromName);
                mail.Sender = mail.ReplyTo;

                if (to.Contains(";"))
                {
                    string[] _EmailsTO = to.Split(";".ToCharArray());

                    for (int i = 0; i < _EmailsTO.Length; i++)
                    {
                        mail.To.Add(new MailAddress(_EmailsTO[i]));
                    }
                }
                else
                {
                    if (!to.Equals(string.Empty))
                    {
                        mail.To.Add(new MailAddress(to));
                    }
                }

                //CC
                if (cc.Contains(";"))
                {
                    string[] _EmailsCC = cc.Split(";".ToCharArray());

                    for (int i = 0; i < _EmailsCC.Length; i++)
                    {
                        mail.CC.Add(new MailAddress(_EmailsCC[i]));
                    }
                }
                else
                {
                    if (!cc.Equals(string.Empty))
                    {
                        mail.CC.Add(new MailAddress(cc));
                    }
                }

                //BCC
                if (bcc.Contains(";"))
                {
                    string[] _EmailsBCC = bcc.Split(";".ToCharArray());
                    for (int i = 0; i < _EmailsBCC.Length; i++)
                    {
                        mail.Bcc.Add(new MailAddress(_EmailsBCC[i]));
                    }
                }
                else
                {
                    if (!bcc.Equals(string.Empty))
                    {
                        mail.Bcc.Add(new MailAddress(cc));
                    }
                }

                string message = "this is a test message";
                mail.Subject = "test subject";
                mail.Body = "<div style=\"font: 11px verdana, arial\">";
                mail.Body += message.Replace("\n", "<br />") + "<br /><br />";
                mail.Body += "<hr /><br />";
                mail.Body += "<h3>Sender information</h3>";
                mail.Body += "<div style=\"font-size:10px;line-height:16px\">";
                mail.Body += "<strong>Name:</strong> " + fromName + "<br />";
                mail.Body += "<strong>E-mail:</strong> " + from + "<br />";
                mail.IsBodyHtml = true;
 
                if (HttpContext.Current != null)
 
                {
 
                    mail.Body += "<strong>IP 
address:</strong> " + HttpContext.Current.Request.UserHostAddress +
"<br />";
                    mail.Body += "<strong>User-agent:</strong> " + HttpContext.Current.Request.UserAgent;
                }
 
                //attachment
                if (attachment != null)
                {
                    mail.Attachments.Add(attachment);
                }

                client.Send(mail);
                emailStatus = "success";
            }
        }

        catch (Exception ex)

        {
            emailStatus = ex.Message;

        } // end try 

        return emailStatus;
    }

Explanation


The sample code is very straight forward and comments are included in it. 

To send email using the mail server information in the web.config file. 

     string status = SendEmail(true); 

If you want to send attachment, include the file location. For instance. 

     Attachment attachment = new Attachment("c:\xyz.pdf"); 

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor