System.Net.Mail FAQ

Complete FAQ Listing


3.4.2 How do I create an attachment from a stream? Printer Friendly

Something that is new in System.Net.Mail, is the capability to create attachments from streams. With this capability we can create an attachment from text, binary data, or from basically anything in memory. We simply need to make sure it is written to a stream.

The following example creates an attachment from some simple text, but it could have just as easily have come from Sql Server.

[ C# ]

static void AttachmentFromStream()
{

//create the mail message
MailMessage mail = new MailMessage();

//set the addresses
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");

//set the content
mail.Subject = "This is an email";
mail.Body = "this content is in the body";

//Get some binary data
byte[] data = GetData();

//save the data to a memory stream
MemoryStream ms = new MemoryStream(data);

//create the attachment from a stream. Be sure to name the data with a file and 
//media type that is respective of the data
mail.Attachments.Add( new Attachment( ms, "example.txt", "text/plain" ));

//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(mail);
}
static byte[] GetData()
{
//this method just returns some binary data.
//it could come from anywhere, such as Sql Server
string s = "this is some text";
byte[] data = Encoding.ASCII.GetBytes(s);
return data;
}



[ VB.NET ]
Sub AttachmentFromStream()

'create the mail message
Dim mail As New MailMessage()

'set the addresses
mail.From = New MailAddress("me@mycompany.com")
mail.To.Add("you@yourcompany.com")

'set the content
mail.Subject = "This is an email"
mail.Body = "this content is in the body"

'Get some binary data
Dim data As Byte() = GetData()

'save the data to a memory stream
Dim ms As New MemoryStream(data)

'create the attachment from a stream. Be sure to name the data with a file and 
'media type that is respective of the data
mail.Attachments.Add(New Attachment(ms, "example.txt", "text/plain"))

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'AttachmentFromStream

Function GetData() As Byte()
'this method just returns some binary data.
'it could come from anywhere, such as Sql Server
Dim s As String = "this is some text"
Dim data As Byte() = Encoding.ASCII.GetBytes(s)
Return data
End Function 'GetData