Wednesday, October 18, 2006

Sending emails using SMTP


Ok this is a common requirement that all my projects need. I use the SmtpClient and MailMessage in the System.Net.Mail namespace.

In .NET1.0 these classes were found in System.Net.Mail namespace from the System.Web.dll.

In .NET2.0 these classes are now found in the System.dll assembly, which simply extends the functionality found from .NET1.0.

To specify default settings for the SmtpClient use the section of the machine or application configuration files.

When sending messages you use the SmtpClient.Send or SmtpClient.SendAsync. No explanation needed here...


Sample code:

using System.Net;
using System.Net.Mail;

SmtpClient client = new SmtpClient("mail.server.address.com",25);
client.Credentials = new NetworkCredential("user@company.com","password");

using (MailMessage msg = new MailMessage()){
--msg.From = "";
--msg.Subject = "";
--msg.Body = "";
--msg.Attachments.Add( new Attachment(@"..\..\file.zip", "application/zip"));
--msg.To.Add(new MailAddress("LiquidBoy@RipThatPage.com"));
--client.Send(msg);
}

No comments: