Thursday, July 05, 2007

Sending emails with C#

I'm sure many may already know how to do this, but for those that don't, sending an email using .NET is very easy and can be used in ASP.NET as well as Windows Forms or Console applications (assuming you have CDOSYS installed). This example also shows how to send an email to multiple recipients (requires you to import the namespace System.Collections).

.NET 1.0 / 1.1 (import the namespace System.Web.Mail)
MailMessage m;
SmtpMail.SmtpServer = "smtpservername";
ArrayList recipients = new ArrayList();
recipients.Add("fred@bloggs.com");
recipients.Add("jane@doe.com");
for (int i = 0;i < recipients.Count;i++)
{
 m = new MailMessage();
 m.To = recipients[i].ToString();
 m.From = "me@mysite.com";
 m.BodyFormat = MailFormat.Html;
 m.Subject = "Subject of the email";
 m.Body = String.Format(
  "<p style='font: 12px Arial'>Sending email to {0}</p>",
  recipients[i]
 );
 SmtpMail.Send(m);
}
.NET 2.0+ (import the namespace System.Net.Mail)
MailMessage m;
SmtpClient smtp = new SmtpClient("smtpservername");
ArrayList recipients = new ArrayList();
recipients.Add("fred@bloggs.com");
recipients.Add("jane@doe.com");
for (int i = 0;i < recipients.Count;i++)
{
 m = new MailMessage();
 m.To = recipients[i].ToString();
 m.From = "me@mysite.com";
 m.IsBodyHtml = true;
 m.Subject = "Subject of the email";
 m.Body = String.Format(
  "<p style='font: 12px Arial'>Sending email to {0}</p>",
  recipients[i]
 );
 smtp.Send(m);
}

No comments: