Thursday, November 29, 2012

How to send mail using CSharp ( c# ) code

In this post we going to see how to send a SMTP mail using CSharp code. A simple csharp code is shown below
 public void SendMail()  
 {  
   try  
   {  
     string fromMail = "ENTER FROM MAIL ADDRESS";  
     string toMail= "ENTER TO MAIL ADDRESS";  
     string smtpServer="ENTER SMTP SERVER ADDRESS HERE";  
     string subject="ENTER SUBJECT HERE";  
     string bodyMessage="ENTER BODY MESSAGE HERE";  
     string password="ENTER YOUR PASSWORD HERE";  
     MailMessage MyMailMessage = new MailMessage();  
     MyMailMessage.From = new MailAddress(fromMail );  
     MyMailMessage.To.Add(toMail);  
     MyMailMessage.Subject = subject;  
     MyMailMessage.Body = bodyMessage;  
     MyMailMessage.IsBodyHtml = false;  
     SmtpClient client = new SmtpClient(smtpServer);  
     client.Port = 25;  
     client.Credentials = new System.Net.NetworkCredential(fromMail , password);  
     client.EnableSsl = true;  
     client.Send(MyMailMessage);  
   }  
   catch (Exception ex)  
   {  
     throw ex;  
   }  
 }  
if you want to send mail using Gmail SMTP use the smtp.gmail.com SMTP Server and the port should be 25.

Note: You have to add System.Net.Mail namespace to make this code work.

No comments:

Post a Comment