Add attacments while sending email in .NET

You can send email from a .net application using System.Net.Mail.MailMessage namespace. It is very simple to send email using this.

// Be sure to include these namespaces
using System.Net.Mail;
using System.IO;
.....
.....
MailMessage message = new MailMessage();

message.From = new MailAddress("someone@example.com");
message.To.Add(new MailAddress("someone@example.com"));
message.Subject = "Simple email";
message.Body = "Hi, this is a email test";
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.example.com");
		smtp.Send(message);

However you in case you can also include attachments with your email in case you need it.

// Be sure to include these namespaces
using System.Net.Mail;
using System.IO;
.....
.....
MailMessage message = new MailMessage();

message.From = new MailAddress("someone@example.com");
message.To.Add(new MailAddress("someone@example.com"));
message.Subject = "Email with attchment";
message.Body = "Hi, this is a attachment test";
message.IsBodyHtml = true;

string filePath = @"C:\\DailyCoding\\DailyCoding.zip";
using (FileStream reader 
	= new FileStream(filePath, FileMode.Open))
{
	byte[] data = new byte[reader.Length];
	reader.Read(data, 0, (int)reader.Length);
	using (MemoryStream ms = new MemoryStream(data))
	{
		message.Attachments.Add(
			new Attachment(ms, "DailyCoding.zip"));
		SmtpClient smtp = new SmtpClient("smtp.example.com");
		smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
		smtp.Send(message);
	}
}

2 comment(S)


Test on Dec 20, 2008 03:22 AM

Test

Montoo on Apr 11, 2009 06:49 AM


Leave a comment