Sending Email Attachments with ‘Friendly’ Names in .NET 2.0
I can across a problem today where I had to attach a PDF file that is stored on a network share to an outgoing email using ASP.NET 2.0. This is pretty simple to do, except in my case the PDF filename on the share has an obfuscated name while its original name (file.pdf) is stored in a database lookup table. Looking at the System.Net.Mail.Attachment constructors, you'll see that three take a string filename and three take a System.IO.Stream object to represent the file. The string filename constructors do not possess the ability (as far as I could see) to give the attached file a "friendly name", although one of the Stream constructors does. So what I ended up doing was opening the file with a non-locking FileStream object and then passing it to the mail attachment object, careful to close the stream when I was done. Pretty simple, but I couldn't find any sources using this method so I thought I'd write it down here (minus error handling code for clarity):
System.Net.Mail.MailMessage message =new System.Net.Mail.MailMessage("from@from.com", "to@to.com", "Subject", "My attachment has a friendly name");
//Open the filestream with non-locking read permission
System.IO.FileStream fileStream = new System.IO.FileStream("fileSystemName", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
message.Attachments.Add(new System.Net.Mail.Attachment(fileStream, "friendlyName.pdf"));
fileStream.Close();