Title : Create Emails and send using your .Net Code
Author : Prabhakar Manikonda
Email : <A href="mailto:email2prabhakar@gmail.comEnvironment">mailto:email2prabhakar@gmail.com
Environment</A>: ASP.NET 1.1
Keywords : Email Client, send emails,attach files.
Level : Intermediate
Description: Use Simple ASP.Net code to send emails.
Section : Web Technology
Introduction
Sending an email is easy we can do it using the general approach that is either using System.web.mail [ASP.NET 1.1] or System.Net.mail [ASP.NET 2.0], but there is another third-party library which we can use if we want, some people do not use this as they say it will yield compatibility issues, but it has been tested and it is in use, even i will prefer to use the Microsoft API rather that DotNetOpenMail API but we being engineer has to know each and every library which has high frequency of usage, The DotNetOpenMail - an SMTP client library for .net, written in C#. This will allow you to minimize your code to create basic text and html emails with attachments that can be sent via an SMTP server.
you can get this library from http://sourceforge.net/projects/dotnetopenmail/
It is a freely available open-source component makes it easy to create HTML and plain text email with file attachments without needing the System.Web.Mail library.
Using the code
Just add the DotNetOpenMail.dll to references and then write the below code
using DotNetOpenMail;
using DotNetOpenMail.Logging;
using DotNetOpenMail.Encoding;
using DotNetOpenMail.Resources;
using DotNetOpenMail.SmtpAuth;
Using DotNetOpenMail is very simple the below code will let you know this fact.
EmailMessage emailMessage = new EmailMessage();
emailMessage.FromAddress = new EmailAddress("senderID@domainName.com");
emailMessage.AddToAddress(new EmailAddress("receiverID@domainName.com"));
emailMessage.Subject = "Subject of the Message";
emailMessage.HtmlPart = new HtmlAttachment("<html><body><p>Write Down some BODY-Text here</p></body></html>");
SmtpServer smtpServer=new SmtpServer("smtpout.domainName.com");
smtpServer.SmtpAuthToken=new SmtpAuthToken("webmaster@domainName.com", "password");
emailMessage.ContentType = "TEXT/HTML";
emailMessage.Send(smtpServer);
Response.Write (" Email Successfully Sent");
Attaching The Files to your Message
Here is the sample code to attach a sample text file
MemoryStream memStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memStream);
writer.WriteLine(" HELLO WORLD ! ");
writer.Flush();
memStream.Seek(0, SeekOrigin.Begin);
FileAttachment attachment = new FileAttachment(new StreamReader(memStream));
attachment.FileName = "Hello.txt";
attachment.CharSet = System.Text.Encoding.ASCII;
attachment.ContentType = "text/plain";
emailMessage.AddMixedAttachment(attachment);
Using dotnetopenmail is very easy and I hope that it will be useful to you.
History
Version 1.0 Release 2006