Thursday, November 29, 2012

How to send smtp mail with attachment using CSharp ( c#)

In this post we going to see how to add a attachment in 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;  
     OpenFileDialog ofd = new OpenFileDialog();  
     ofd.ShowDialog();  
     Attachment attachment = new Attachment(ofd.FileName);  
     MyMailMessage.Attachments.Add(attachment);  
     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;  
   }  
 }  
In the above code i have used OpenFileDialog to let the user to select the attachment to send through mail. Note: You have to add System.Net.Mail namespace to make this code work.

No comments:

Post a Comment