How to Send an Email with Attachment

In old era, letters were used to share your feelings, thoughts and emotions (in word expression). But now days, you may share these all things in their real form as you desire via new technology (Email). There are many websites that provides you email facility as Hotmail, Yahoo. If you are programmer and you want to send an email via your application then it is very interesting idea.

 

Now, Question is how? It is be very simple way. In .net, this functionality is already build-in. you just need to call that DLL file as reference and use it. Two DLL files use 'System.Net.Mail' and 'System.Web.Mail'.

 

In my example, I am using 'system.web.mail' which send my mail with single attachment. You may send multiple attachments by creating an object of Mail Attachment then add number of files and then assign to attachment property.

 

I am creating an object of  'MailMessage' and assigns emails to TO and FROM property and set text message to body property and attachment (its single attachment) then make a new object of SmtpMail and sets local server (from where to send) then call its property Send and assign the MailMessage object. Now call this function, you email is ready to send. 

 

NOTE: Smtp server name will be your server name or IP

 

public void SendMail(string mailFrom, string mailTo, string copyTo)

{

     mail = new MailMessage();

     mail.From = mailFrom;

     mail.To = mailTo;

     mail.Cc = copyTo;

     mail.Subject = this.subject;

     mail.Attachments.Add(new MailAttachment("c:\test.txt");

     mail.Body = this.body;

     mail.Priority = MailPriority.High;

     mail.BodyFormat = MailFormat.Text;

     SmtpMail.SmtpServer = "172.16.0.23";

     SmtpMail.Send(mail);

}


Similar Articles