How to send emails in .NET part 5: attachments

Adding an attachment to a MailMessage object can be as simple as inserting an Attachment object to the Attachments collection:

string from = "";
string to = "";
string subject = "Testing email attachment";
string plainTextBody = "This is a great message.";
MailMessage mailMessage = new MailMessage(from, to, subject, plainTextBody);

mailMessage.Attachments.Add(new Attachment(@"C:\logfile.txt"));

string smtpServer = "";
SmtpClient client = new SmtpClient(smtpServer);

You can also specify the MIME type – Multipurpose Internet Mail Extensions – using the MediaTypeNames enumeration. E.g. you can add an attachment as a Stream in the following way:

Stream attachmentStream = new FileStream(@"C:\logfile.txt", FileMode.Open, FileAccess.Read);
mailMessage.Attachments.Add(new Attachment(attachmentStream, "recent_log.txt", MediaTypeNames.Text.Plain));

Note that you can specify a different file name in the Attachment constructor. It can differ from the name of the original source. You can even change its extension if you want, such as “myfile.html”. If you’re not sure of the MIME type you can use MediaTypeNames.Application.Octet which indicates a binary file.

Read all posts related to emailing in .NET here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to How to send emails in .NET part 5: attachments

  1. Morteza says:

    I remember a few months a go a colleague of mine had a funny issue with sending attachment alongside email.

    After sending an email, surprisingly there was no attachment out there! Everything was fine and the code was quite simple and small. After some investigation we found out the issue was due to the size of the attachment. It was several MB and we had to increase the Timeout for SmtpClient object.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: