Tuesday, July 22, 2008

Send Email .NET code using Gmail SMTP

To send email, we need a SMTP server and Google has provided it for free :) Just use this code to send email using your Gmail account.

public static void SendMail()

        {

            //Builed The MSG 

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

            msg.To.Add("agus.santoso@plasmedia.com");           

            msg.From = new MailAddress("youremail@gmail.com", "Your Name",System.Text.Encoding.UTF8);

            msg.Subject = "Test mail using .net2.0";

            msg.SubjectEncoding = System.Text.Encoding.UTF8;

            msg.Body = "This is my msg Body";

            msg.BodyEncoding = System.Text.Encoding.UTF8;

            msg.IsBodyHtml = false;

            msg.Priority = MailPriority.High;           

          

            //Add the Creddentials 

            SmtpClient client = new SmtpClient();

            client.Credentials = new System.Net.NetworkCredential("youremail@gmail.com", "your password");

            client.Port = 587; 

            client.Host = "smtp.gmail.com";

            client.EnableSsl = true;

            object userState=msg;

            try

            {

                client.Send(msg);

                Console.WriteLine("success");

            }

            catch (System.Net.Mail.SmtpException ex)

            {

              Console.WriteLine("Send Mail Error");

            }

        }

No comments: