code first, ask questions later

Simple C# Synchronous / Asynchronous Email Sender

UPDATE: I am now using a Fluent Email Class that implements similar techniques.

I noticed quite a few search queries coming in for my post on User Control Email Templates so I thought I should post the code I am using to actually send the emails in that example. The class uses the SMTP configuration information in the web.config or app.config of the application. An example of the config is after the code.

The code is pretty quick and dirty but if you are only sending one off emails it works fine.

    

public static class EmailSender
{
	///
	/// Sends an Email.
	///
	public static bool Send(string sender, string senderName, string recipient, string recipientName, string subject, string body)
	{
		var message = new MailMessage()
		{
			From = new MailAddress(sender, senderName),
			Subject = subject,
			Body = body,
			IsBodyHtml = true
		};
		
		message.To.Add(new MailAddress(recipient, recipientName));

		try
		{
			var client = new SmtpClient();
			client.Send(message);
		}
		catch (Exception ex)
		{
			//handle exeption
			return false;
		}

		return true;
	}

	///
	/// Sends an Email asynchronously
	///
	public static void SendAsync(string sender, string senderName, string recipient, string recipientName, string subject, string body)
	{
		var message = new MailMessage()
			{
				From = new MailAddress(sender, senderName),
				Subject = subject,
				Body = body,
				IsBodyHtml = true
			};
		message.To.Add(new MailAddress(recipient, recipientName));

		var client = new SmtpClient();
		client.SendCompleted += MailDeliveryComplete;
		client.SendAsync(message, message);
	}

	private static void MailDeliveryComplete(object sender, AsyncCompletedEventArgs e)
	{
		if (e.Error != null)
		{
			//handle error
		}
		else if (e.Cancelled)
		{
			//handle cancelled
		}
		else
		{
			//handle sent email
			MailMessage message = (MailMessage)e.UserState;
		}
	}
}

Here is an example of the mailSettings config section.

    <system.net>
      <mailSettings>
        <smtp from="test@test.test">
          <network host="smtphost" port="25" username="user" password="password" defaultCredentials="true" />
        </smtp>
      </mailSettings>
    </system.net>
blog comments powered by Disqus