If your reading this, then chances are you've looked how to create a simple email with C# and added some HTML in there. You might have then looked for including images and the documentation on the internet for this is kinda poor/bad/doesn't work. Well here's how!!
In this example, I have created a class library that can be used with any C# application. So it doesn't matter what kinda application you have (MVC, ASPX Web App, Client App, Command Line etc...).
Lets let on with it!! I've created this project in .NET 4.0 at time of writing and included a VS2010 MVC3 Web App with it for full example. I have also included some global MVC3 error handling!
Code Snippet
- // <copyright file="EmailHelper.cs" company="GinkoSolutions.com">
- // Copyright (c) 2011 All Right Reserved
- // </copyright>
- // <author>Sean Greasley</author>
- // <email>sean@ginkosolutions.com/sean@tutorialgenius.com</email>
- // <summary>Email helper class. Allows sending of html and plain text emails to a target email address.</summary>
- namespace MVCEmailExample.Helpers
- {
- using System;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.Configuration;
- using System.Linq;
- using System.Net.Mail;
- using System.Net.Mime;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using MVCEmailExample.Exceptions;
- using MVCEmailExample.Models;
- /// <summary>
- /// Email helper class.
- /// Allows sending of html and plain text emails to a target email address.
- /// </summary>
- public class EmailHelper
- {
- /// <summary>
- /// Sends an email to a recipient. Provides HTML and plain text views.
- /// The recipient will receive which one their client supports.
- /// </summary>
- /// <param name="templateDir">Directory of where the HTML email template is stored.</param>
- /// <param name="recipient">Receipient information</param>
- public static void SendEmail(string templateDir, Recipient recipient)
- {
- try
- {
- // Build message
- message.Subject = ConfigurationManager.AppSettings["EmailSubject"];
- // Create plain text mode for alternative view
- AlternateView plainView = AlternateView.CreateAlternateViewFromString(ConfigurationManager.AppSettings["PlainTextEmail"], null, "text/plain");
- message.AlternateViews.Add(plainView);
- // Create HTML email version
- mailDef.BodyFileName = string.Format(@"{0}\{1}", templateDir, @"Email.html");
- mailDef.IsBodyHtml = true;
- mailDef.Subject = ConfigurationManager.AppSettings["EmailSubject"];
- // Build replacement collection to replace fields in Email.htm file
- // Use fields anywhere in the template file. I.e. <%FRIENDNAME%>
- replacements.Add("<%NAME%>", recipient.Name);
- // Use dummy control as owner (I.e. new System.Web.UI.Control()) as were in a class library.
- // It's only use to determine where the access templates from as a relative base.
- MailMessage msgHtml = mailDef.CreateMailMessage(recipient.Email, replacements, new System.Web.UI.Control());
- AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, null, "text/html");
- // Add linked resources
- AddLinkedResources(templateDir, ref htmlView);
- // Add HTML view
- message.AlternateViews.Add(htmlView);
- // Send message
- client.Send(message);
- }
- }
- /// <summary>
- /// Adds linked resources to the email
- /// Email template must contain the resource IDs in the following format: <img src="cid:CONTENTID" />
- /// </summary>
- /// <param name="templateDir">Directory of where the HTML email template images are stored.</param>
- /// <param name="htmlView">A reference to the HTML view.</param>
- private static void AddLinkedResources(string templateDir, ref AlternateView htmlView)
- {
- LinkedResource logo1 = new LinkedResource(string.Format(@"{0}\{1}", templateDir, @"Images\email.jpg"), MediaTypeNames.Image.Jpeg);
- logo1.ContentId = "email";
- htmlView.LinkedResources.Add(logo1);
- }
- }
- }
End of Code Snippet
Note: This will attempt to send a HTML email with an embedded image (linked resource). If the client does not support HTML, then a plain text email will be used as backup. boom! (I've defined this in the application settings, as well as the email subject and "from" email address).
Configuration - App Settings (Optional, just didn't want to hard code them) [Web/App.config]
Code Snippet
- <appSettings>
- <!-- Email App Settings -->
- <add key="EmailSubject" value="GinkoSolutions.com Email Example"/>
- <add key="PlainTextEmail" value="Hi There, You currently don't support HTML emails, but thats ok! I'm just saying hello anyway!"/>
- </appSettings>
End of Code Snippet
Configuration - Email server [App/Web.config]
Code Snippet
- <system.net>
- <mailSettings>
- <smtp from="Admin <admin@ginkosolutions.com>">
- <network host="localhost" port="25" />
- </smtp>
- </mailSettings>
- </system.net>
End of Code Snippet
Note: This won't work unless you have a local email server. Please provide the details to an SMTP email server here.
Create a sample recipient class (Just for storing recipient details)
Code Snippet
- public class Recipient
- {
- public string Name { get; set; }
- public string Email { get; set; }
- }
End of Code Snippet
Invoke the email static class
Code Snippet
- // Construct recipient from form
- // Send email
- EmailHelper.SendEmail(Server.MapPath("~/EmailTemplate"), recipient);
End of Code Snippet
Note: I have added an email template path as a parameter. This is so that if you execute the email helper from a web application, it knows where to find the templates!
Sample HTML Template File
Code Snippet
- <body style="background: #000000;">
- Hello <%NAME%>,
- I thought i'd send you a picture of some guy holding an envelope.
- <img src="cid:email" />
- I have no idea why though!
- Thanks!
- </body>
End of Code Snippet
Note:
Notice the cid prefix for the images. This indicates a contentID for a linked resource. If you look in the code for the email helper, you will notice that I am created 1 linked resource and setting the contentID to 'email'. This will simply embed the image.
Again, in this template, you will notice I have used a custom tag for the friend's name called NAME. This is replaced within the email helper when we construct a ListDictionary and add our replacements to it.
and thats it!!
If you stuck, or can't get it to compile, then download the full sample here
MVC3 Web Application - Full Email Example with Fallback
1 comment:
The link to the full project is broken; any chance that can be restored?
Also can you please consider revising this or publishing a separate article for VS2013/.Net 4.5 ?
Post a Comment