Wednesday, September 16, 2009

Sending Email using C#

While it is not difficult to send email via C#, there tends to be a lot of code that I put in place every time. For starts I like to have a class or at least one method that all email in the application go through. The main reason is so that I can quickly see where the method is called and see where emails are sent. This also aids in debugging, and understanding of code when someone comes onto the project.

One of the first things asked is, how do I turn off emails during development. This provides one location that can be commented out. I take it one step further and make it web.config setting. When email is disabled, I still would like to see a log that it would have been sent. So, I have a log file that the email is written to instead of actually sending the email. The log is only used for development purposes.

I also like to have default email to/from incase the unexpected case of no to/from is encounter when I am not expecting it to. This way I am notified. I also pull the smtp server from the web.config instead of hard coding it. You may also notice I call something I call Config instead of accessing the web.config directly. This is because, I again like to have all access my app settings in one class that can be easily changed if needed. For example, in certain instances configuration may need to be stored in a database instead of the config file. This makes that change very easy to make just by changing and testing one class.

Below is the method / code snippet I use:

public void SendEmail(string fromEmailAddress, string toEmailAddress, string subject, string body, HttpPostedFile attachment)
{
// this should never happen, but just so I will know about it
if (string.IsNullOrEmpty(toEmailAddress))
{
toEmailAddress = "myemail@mydomain.com";
}
// this should never happen, but just so I will know about it
if (string.IsNullOrEmpty(fromEmailAddress))
{
fromEmailAddress = "myemail@mydomain.com";
}

MailMessage msg = new MailMessage(fromEmailAddress, toEmailAddress, subject, body);
Attachment attachmentItem;
if (attachment != null)
{
attachmentItem = new Attachment(attachment.InputStream, attachment.FileName);
msg.Attachments.Add(attachmentItem);
}

msg.IsBodyHtml = false;

SmtpClient smtp = new SmtpClient();
smtp.Host = Config.SmtpServer;

if (Config.AllowEmailsToBeSent)
{
smtp.Send(msg);
}
else
{

StreamWriter writer = new StreamWriter(@"c:\Email.log", true);
using (writer)
{
writer.WriteLine("\r\n\r\nDate/Time Stamp: " + DateTime.Now.ToLocalTime());
writer.WriteLine("From: " + msg.From.Address);
writer.WriteLine("To: " + msg.To[0].Address);
writer.WriteLine("Subject: " + msg.Subject);
writer.WriteLine("Body: " + msg.Body);
if (attachment != null)
{
writer.WriteLine(string.Format("Attachment: {0}", msg.Attachments[0].Name));
}
}
}
}

No comments: