System.Net.Mail FAQ

Complete FAQ Listing


3.4.1 How do I send an email with attachments? Printer Friendly

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.  If the file is found in the website, we don't need use the explicit file path, we could also call Server.MapPath(...).

Below is a simple example of attaching  text files to an outgoing email.

[ C# ]

static void AttachmentFromFile()
{
//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";

//add an attachment from the filesystem
mail.Attachments.Add(new Attachment("c:\\temp\\example.txt"));

//to add additional attachments, simply call .Add(...) again
mail.Attachments.Add(new Attachment("c:\\temp\\example2.txt"));
mail.Attachments.Add(new Attachment("c:\\temp\\example3.txt"));

//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(mail);

}


[ VB.NET ]
Sub AttachmentFromFile()
'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"

'add an attachment from the filesystem
mail.Attachments.Add(New Attachment("c:\temp\example.txt"))

'to add additional attachments, simply call .Add(...) again
mail.Attachments.Add(New Attachment("c:\temp\example2.txt"))
mail.Attachments.Add(New Attachment("c:\temp\example3.txt"))

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