Attach Files to mail using C#

Attach Files to mail using C#

To attach a file, add it to the MailMessage.Attachments AttachmentCollection by calling the MailMessage.Attachments.Add method. The simplest way to add a file is to specify the file name



' VB
Dim m As MailMessage = New MailMessage()
m.Attachments.Add(New Attachment("C:\boot.ini"))

// C#
MailMessage m = new MailMessage();
m.Attachments.Add(new Attachment(@"C:\boot.ini"));

You can also specify a MIME (Multipurpose Internet Mail Extensions) content type using the System.Net.Mime.MediaTypeNames enumeration. There are special MIME types for text and images, but you will typically specify MediaTypeNames.Application.Octet. The following code sample (which requires System.IO and System.Net.Mime in addition to System.Net.Mail) demonstrates how to use a Stream as a file attachment and how to specify the MIME type:

' VB
Dim m As MailMessage = New MailMessage()
Dim sr As Stream = New FileStream("C:\Boot.ini", FileMode.Open, FileAccess.Read)
m.Attachments.Add(New Attachment(sr, "myfile.txt", MediaTypeNames.Application.Octet))

// C#
MailMessage m = new MailMessage();
Stream sr = new FileStream(@"C:\Boot.ini", FileMode.Open, FileAccess.Read);
m.Attachments.Add(new Attachment(sr, "myfile.txt", MediaTypeNames.Application.Octet));




Comments

Author: Prakash kumar pothal18 Feb 2010 Member Level: Gold   Points : 1

Attach Files to mail using C#

MailMessage Message = new MailMessage();
Message.Attachments.Add(new Attachment(ContentPath));

ContentPath --> this the attached file.


Regards,
prakash

Author: Jayendra Kumar19 Feb 2010 Member Level: Gold   Points : 0

Thanks to share this information.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: