Attaching files to emails in .NET is easy if you’ve physically saved the file on the server. What if you don’t want to save the file, though? It’s actually pretty simple as well, but you need to convert the data to be attached into a Stream.
The following code converts some plain old text into a MemoryStream and then attaches it to an email message as a .txt file. The same can be done with any other type of data, you just need the appropriate MemoryStream.
// import these:
using System.Net.Mail;
using System.IO;
using System.Text;
// inside your class, create a regular old MailMessage object
MailMessage message = new MailMessage();
// TODO: set the message subject, body, recipients, etc...
string fileContents = "Thanks for the code, Jason!";
// you need a MemoryStream in order to create an attachment w/o saving the file
MemoryStream ms = new MemoryStream(
ASCIIEncoding.ASCII.GetBytes(fileContents)
);
// now that you have a MemoryStream, attaching it is easy:
message.Attachments.Add(
new Attachment(ms, "myfile.txt")
);
// TODO: send the message as you normally would
I’ve only included the code relevant to the attachment because everything else is exactly the same as sending an email normally.
If you wanted to do the same with an image file, for example, you might try something like this:
using System.Drawing.Imaging; // TODO: all of the Email stuff from the above example Image img = GetMyImage(); // assuming GetMyImage returns System.Drawing.Image MemoryStream ms = new MemoryStream(); img.Save(ms, ImageFormat.Png); // TODO: the rest of the attachment process is the same as above
Peter
June 3, 2009 at 2:25 pm
Thats was a pretty crappy tutorial.
If youre just gonna write; “the rest of the attachment process is the same” then you might as well just avoid making any tutorial.
Now Im wondering how I am supposed to attach the image to the html body of the mail.
Jason
June 3, 2009 at 8:52 pm
Hey Peter, this code is only for attaching files, not embedding images into the email body. There’s plenty of examples out there for sending multi-part messages.
I only write things that I encounter and need to use in my own work. I can’t guarantee they’ll work for you or anybody else, I only know it was useful to me at one point.