Pages

Thursday, August 15, 2013

How to send mail from Gmail address to any mail address using C# code and SMTP.

It is easy to send mail from your email account to another email using gmail smtp server, Here the sample code in C#,  you should have to add the following class files in includes,

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

Here is the complete code,

            MailMessage mail = new MailMessage();
            string from = "fromemailaddress@gmail.com"; // your gmail address
            string pass = "yourpassword";  // your gmail password
            mail.From = new MailAddress(from);
            mail.To.Add("tomailaddress@gmail.com");  //to mail address
            mail.Subject = "This is test mail from smtp";
            mail.Body = "This is my test mail sending from SMTP ";
            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
            smtp.EnableSsl = true;
            smtp.Credentials = new NetworkCredential(from, pass);
            try
            {
                smtp.Send(mail);

            }
            catch (Exception ex)
            {
                throw new System.Exception(ex.Message);
            }

No comments:

Post a Comment