I was developing ASP.NET application recently which one of basic functionality was sending emails to its users.
I decided that sending html emails will be much more cool then just in plain text.
Below is an example, how this can be done. This code sends email both in HTML and plain text.

// Required imports
using System.Net.Mail;
using System.Collections.Generic;

// SMTP settings
private string smtpHost = "smtp.mail.server";
private string smtpUser = "user@mail.server";
private string smtpPass = "smtpPassword";
private int smtpPort = 25;

/// <summary>
/// Function sends email to the given addresses.
/// </summary>
/// <param name="sender">Sender email address</param>
/// <param name="recipients">Array of recipients addresses</param>
/// <param name="subject">Message subject</param>
/// <param name="html">Html message body</param>
/// <param name="text">Text message body</param>
/// <param name="replacements">List of items to replace in the message</param>
public void SendEmail(
    string sender
    , string[] recipients
    , string subject
    , string html
    , string text
    , ListDictionary replacements)
{
    try
    {
        if (sender == null)
            throw new Exception("From address is required!");

        if (recipients.Count() <= 0)
            throw new Exception("No recipients found!");

        if (string.IsNullOrEmpty(subject))
            throw new Exception("Subject is required!");

        if (string.IsNullOrEmpty(html))
            throw new Exception("HTML body is required!");

        if (string.IsNullOrEmpty(text))
            throw new Exception("Text body is required!");

        // Create email message
        var message = new MailMessage();
        message.Subject = subject;
        message.From = new MailAddress(sender);
        message.To.Add(string.Join(",", recipients));

        // Create plain text email definition
        // -----------------------------------------------
        MailDefinition plainMessage = new MailDefinition();
        plainMessage.IsBodyHtml = false; // false for body in plain text
        plainMessage.From = sender;
        plainMessage.Subject = subject;

        // Create proper plain text message
        MailMessage msgPlain = plainMessage.CreateMailMessage(
        string.Join(",", recipients)  // list of recipients
            , replacements                // dictionary list for replacements in body
            , text                        // message body
            , new System.Web.UI.Control() // owner
        );

        // Create and add alternative view to email message with media type text/plain
        AlternateView plainView = AlternateView.CreateAlternateViewFromString(
            msgPlain.Body
            , null
            , "text/plain");
        message.AlternateViews.Add(plainView);

        // Create html email definition
        // -----------------------------------------------
        MailDefinition htmlMessage = new MailDefinition();
        htmlMessage.IsBodyHtml = true; // true for html body
        htmlMessage.From = sender;
        htmlMessage.Subject = subject;
        MailMessage msgHtml = htmlMessage.CreateMailMessage(
            string.Join(",", recipients)  // list of recipients
            , replacements                // dictionary list for replacements in body
            , html                        // message body
            , new System.Web.UI.Control() // owner
        );

        // Create and add alternative view to email message with media type text/html
        AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
            msgHtml.Body
            , null
            , "text/html");
        message.AlternateViews.Add(htmlView);

        // Create smtp client that will send the message
        var client = new SmtpClient()
        {
            Host = smtpHost,
            Port = smtpPort,
            EnableSsl = (25 != smtpPort) ? true : false
        };

        // Set authentication data
        client.Credentials = new System.Net.NetworkCredential(smtpUser, smtpPass);

        // Finally send message
        client.Send(message);
    }
    catch (Exception e)
    {
        // Catch exceptions ...
    }
}

Usage:

SendEmail(
    "admin@ekadry.info"
    , new string[] { "marek@ekadry.info", "emil@ekadry.info" }
    , "Powiadomienie"
    , "<h2>Witaj,</h2><br/>system wysłał do Ciebie powiadomienie dnia <span style="color: #64c1ff;"><%senddata%></span>."
    , "Witaj,rnsystem wysłał do Ciebie powiadomienie dnia <%senddata%>.",
    new ListDictionary() {
        {"<%senddata%>", DateTime.Now.ToShortDateString()}
    });

Emails should look like this:
Email in plain text and html

Facebook comments:

3 responses


Do you want to comment?

Comments RSS and TrackBack Identifier URI ?

Nice, but it would be more general if you would allow sending pure text messages with the same function.

11 August 2011 18 h 53 min

Well, you can always overload this function and check html parameter with String.IsNullOrEmpty() if needed.

11 August 2011 22 h 01 min


Comment now!
















Trackbacks