Wednesday 16 May 2012

How to send email in .Net?or how to send an email from a Gmail address using SMTP server?

Definition: SMTP Server

SMTP protocol is used for sending email . SMTP stands for Simple Mail Transfer Protocol. System.Net.Mail namespace is used for sending email . We can instantiate SmtpClient class and assign the Host and Port . The default port using SMTP is 25 , but it may vary different Mail Servers .
The Gmail SMTP server name is smtp.gmail.com and the port using send mail is 587 and also using NetworkCredential for password based authentication.

Following example shows how to send email in .Net? or How to send email by using your gmail email id?


Example:


using System.Net.Mail;
 
private void SendMail_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                mail.From = new MailAddress("your_gmail_id@gmail.com");
                mail.To.Add("To_emailid@xyz.com");
                mail.Subject = "Test Mail";
                mail.Body = "This is for testing SMTP mail from gmail.";

                SmtpServer.Port = 587;
  SmtpServer.Credentials=new System.Net.NetworkCredential("your_gmail_id@gmail.com", "your_gmail_id_password");
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                MessageBox.Show("Mail Send Successfully");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }



 

No comments:

Post a Comment