<<Back To Faq 2.3


Complete FAQ Listing


2.3 How do I send an email with attachments? Printer Friendly   Email This FAQ   Discuss

To send an email with attachments, the ASP.NET process (or the ASP.NET impersonated account) will need permission to read the file, and attach it to the MailMessage class.

Note: Attachments can only be created from files on the file system. System.Web.Mail does not support creating attachments directly from strings, byte arrays, streams, or from uploaded files. To directly create attachments from these types, use aspNetEmail, otherwise, the attachment contents must first be saved to the file system.

The following example demonstrates adding the file "test.txt" as an attachment to a MailMessage.
 
[ C# ]
MailMessage mail = new MailMessage();
mail.To = "me@mycompany.com";
mail.From = "you@yourcompany.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body.";
MailAttachment attachment = new MailAttachment( Server.MapPath( "test.txt" ) ); //create the attachment
mail.Attachments.Add( attachment );	//add the attachment
SmtpMail.SmtpServer = "localhost";  //your real server goes here
SmtpMail.Send( mail );

[ VB.NET ]
Dim mail As New MailMessage()
mail.To = "me@mycompany.com"
mail.From = "you@yourcompany.com"
mail.Subject = "this is a test email."
mail.Body = "this is my test email body."
Dim attachment As New MailAttachment(Server.MapPath("test.txt")) 'create the attachment
mail.Attachments.Add(attachment) 'add the attachment
SmtpMail.SmtpServer = "localhost" 'your real server goes here
SmtpMail.Send(mail)

 



The formatted version of this faq can be found at http://www.SystemWebMail.com/faq/2.3.aspx