Search 
DailyCoding > General

Add attacments while sending email in .NET

Describes how to include attachemt with MailMessage in .net while sending emails
Author admin on May 22, 2008 0 Comments
Rate it    (Rated 0 by 0 people)
234 Views

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);
	}
}
ASP.NET | C#

Discussion

Leave a Comment

Name
Email Address
Web Site
© Copyright 2008 Daily Coding • All rights reserved