Monday, March 07, 2005

Email Sending in .NET

First you need a SMTP server (relay server) available for your .NET application to send out emails. SMTP server can be a Linux Sendmail demon or IIS SMTP service.

To send an email in .NET 1.1, you need a reference to System.Web.dll and use the System.Web.Mail namespace:

MailMessage emailMsg = new MailMessage();
emailMsg.From =
"sender@mydomain.com";
emailMsg.To =
"receiver@mydomain.com";
emailMsg.Subject =
"Subject";
emailMsg.Body =
"Body";
SmtpMail
.SmtpServer = "mysmtpserver.com";
SmtpMail
.Send(emailMsg);

Be aware that under the hood .NET dispatches email message to a COM library CDO.Message included in cdosys.dll, which come with Windows 2003 server (in $Windows$/system32 folder). So .NET email function is just a wrapper function, and unmanaged (native) code is involved during the email sending.

If SMTP server requires authenitcation, you need to add following setting for MailMessage:

emailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
emailMsg.Fields[
"http://schemas.microsoft.com/cdo/configuration/sendusername"] = "myLogin";

emailMsg.Fields[
"http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "myPassword";

If you want the a HTML format of email, and add an attachment to it:

emailMsg.BodyFormat = MailFormat.Html;
MailAttachment
emailAttchement = new MailAttachment(fileName);
emailMsg.Attachments.Add(emailAttchement);