How to send emails in .NET part 5: attachments
August 27, 2014 1 Comment
Adding an attachment to a MailMessage object can be as simple as inserting an Attachment object to the Attachments collection:
string from = "andras.nemes@company.com"; string to = "john.smith@company.com"; 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 = "mail.apicasystem.com"; SmtpClient client = new SmtpClient(smtpServer); client.Send(mailMessage);
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.
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.