Infolink

 

Search This Blog

Oct 29, 2012

Asp.net sending email with zip file as attachment (PART-12)

In this article I would like to explain how to send the compressed or zip document as an email attachments. You can find the c# source code sample how to send the email with zip format. If you are sending the html attachment or some JavaScript there might be change attachment get corrupted. If you are using the outlook web access (OWA) email client to read the email, there might be change of your html get corrupted because of OWA html filtering option.

Best solution is we can compress the file and attach to email as attachment.  We can find the different approachs to send the email, You can find the below best solution for attachment format.


Sending attachment as PDF format:  You can use ItextSharp library to create the pdf file. You will get the lot of example on how to use the ItextSharp to create the pdf file on .net. I have plan to write one artical on creating the pdf using .net source code.

Sending attachment as zip: You can use opensource library to compress the file and send it as email.  Visit my previous article asp.net file compression

Here I have used C# source code to send the email as attachment. Again I have used opensource DotNetZIP library as compression tool to compress the attachment before sending the email.

MemoryStream memoryStreamOfFile = new MemoryStream();
using (ZipFile zip = new ZipFile())
{
zip.AddEntry("Sample Test.txt", ReadmeText, Encoding.Default);
zip.Password = "Test";
zip.Save(memoryStreamOfFile);
memoryStreamOfFile.Position = 0;
}
Attachment attachment = new Attachment(memoryStreamOfFile, archiveName);
MailMessage message = new MailMessage();
message.From = new MailAddress("<a href="mailto:email@website.com">email@website.com</a>");
message.To.Add(new MailAddress("<a href="mailto:recipient1@website.com">recipient1@website.com</a>"));
message.To.Add(new MailAddress("<a href="mailto:recipient2@website.com">recipient2@website.com</a>"));
message.To.Add(new MailAddress("<a href="mailto:recipient3@website.com">recipient3@website.com</a>"));
message.CC.Add(new MailAddress("<a href="mailto:carboncopy@website.com">carboncopy@website.com</a>"));
message.Subject = "This is my subject";
message.Body = "This is the content";
message.Attachments.Add(attachment);
SmtpClient client = new SmtpClient();
client.Send(message);

In above example Zip.save(memoryStreamOfFile) save the zip file to memorystream format and later memoryStreamOfFile used for email attachment.

1 comment:

Related Posts Plugin for WordPress, Blogger...