.NET MailMessage, LinkedResources, AlternateViews and Exceptions

It doesn’t take much to hack together email functionality using the .NET framework.  In most cases you can new-up a MailMessage reference, assign sender and recipient addresses, provide a subject and a message body, configure your SMTP settings and then send.  Done and done.

But let’s say you need to provide both plain text and HTML versions of your message body.  Or maybe you would like to embed an image or two within the message body.  Or, what if, for some reason, you actually want to handle exceptions appropriately.  Well, there’s more to it then.

There are a numerous ways to better organize the following code.  In fact, we just went through an exercise at work where we refactored the heck out of the core email functionality and produce a really clean usable component which can be easily mocked, configured and leverages email templates.  It’s pretty cool.  That being said, I believe the following sample demonstrates the aforementioned core features of .NET emailing. 

I hope it helps. Let me know if I missed anything or it the example could be more clear.

try
{
    // Assign a sender, recipient and subject to new mail message
    MailAddress sender =
        new MailAddress("sender@johnnycoder.com", "Sender");

    MailAddress recipient =
        new MailAddress("recipient@johnnycoder.com", "Recipient");

    MailMessage m = new MailMessage(sender, recipient);
    m.Subject = "Test Message";

    // Define the plain text alternate view and add to message
    string plainTextBody =
        "You must use an email client that supports HTML messages";

    AlternateView plainTextView =
        AlternateView.CreateAlternateViewFromString(
            plainTextBody, null, MediaTypeNames.Text.Plain);

    m.AlternateViews.Add(plainTextView);

    // Define the html alternate view with embedded image and 
    // add to message. To reference images attached as linked 
    // resources from your HTML message body, use "cid:contentID" 
    // in the <img> tag...
    string htmlBody =
        "<html><body><h1>Picture</h1><br>" +
        "<img src=\"cid:SampleImage\"></body></html>";

    AlternateView htmlView =
        AlternateView.CreateAlternateViewFromString(
            htmlBody, null, MediaTypeNames.Text.Html);

    // ...and then define the actual LinkedResource matching the 
    // ContentID property as found in the image tag. In this case, 
    // the HTML message includes the tag 
    // <img src=\"cid:SampleImage\"> and the following 
    // LinkedResource.ContentId is set to "SampleImage"  
    LinkedResource sampleImage =
        new LinkedResource("sample.jpg", 
            MediaTypeNames.Image.Jpeg);
    sampleImage.ContentId = "SampleImage";
    
    htmlView.LinkedResources.Add(sampleImage);

    m.AlternateViews.Add(htmlView);

    // Finally, configure smtp or alternatively use the 
    // system.net mailSettings
    SmtpClient smtp = new SmtpClient
          {
              Host = "smtp.bigcompany.com",
              UseDefaultCredentials = false,
              Credentials =
                  new NetworkCredential("username", "password")
          };

    //<system.net>
    //    <mailSettings>
    //        <smtp deliveryMethod="Network">
    //            <network host="smtp.bigcompany.com" 
    //              port="25" defaultCredentials="true"/>
    //        </smtp>
    //    </mailSettings>
    //</system.net>

    smtp.Send(m);
}
catch (ArgumentException)
{
    throw new
        ArgumentException("Undefined sender and/or recipient.");
}
catch (FormatException)
{
    throw new
        FormatException("Invalid sender and/or recipient.");
}
catch (InvalidOperationException)
{
    throw new
        InvalidOperationException("Undefined SMTP server.");
}
catch (SmtpFailedRecipientException)
{
    throw new SmtpFailedRecipientException(
        "The mail server says that there is no mailbox for recipient");
}
catch (SmtpException ex)
{
    // Invalid hostnames result in a WebException InnerException that 
    // provides a more descriptive error, so get the base exception
    Exception inner = ex.GetBaseException();
    throw new SmtpException("Could not send message: " + inner.Message);
}

Comments

  1. Dear SIr,

    Kindly Let me know what to pass in content Id in case if i am sending multiple image from database. I tried so many times but it always show the last image of my database in each image. Kindly email me if you have any suggestions.

    i ll wait for your reply.

    regards
    PANKAJ

  2. @Pankaj – You have full control of the contentids. You may include multiple images in htmlBody just makes sure that each image’s contentid is unique. I hope this helps.

  3. Dear Sir,

    Kindly Let me know how to pass multiple images path in (LinkedResource sampleImage =
    new LinkedResource(“sample.jpg”,MediaTypeNames.Image.Jpeg)). If all of my images are stored in a web server.
    if i am using my web server path e.g (http://www.dareadventures.com/folder/IMAGE_NAME) then i m getting a error (URI Formats are not supported). Because LinkedResourse searching the image in local drive e.g. (C:\document and setting……..), But my images are on the web server. So kindly email me if you have any suggestions, how to pass the web server path in LinkedResource.

    I’ll wait for your reply.

    Thanks & regards,
    Ramesh Rana

  4. I like this place very much.

    This is really a outstanding website.
    And it is not like other money orientated site, the info here is really useful.

    I am definitely bookmarking it as well as sharin it with my friends.

    :)

  5. Hi Ben,

    I am having the same issue that Ramesh Rana posted on August 24, 2009. I get the image as an attachment instead of embedded in my html design, in spite of having the src tag properly located.

    Also I have my images in a web server so my paths are all like “http://mywebsite.com/myimages/image.jpg” and when I use this instead of the internal path (c:/myimages/image.jpg) I get the same error.

    Could you please post the answer I guess you already provided to Ramesh?

    Thanks

  6. Sometimes i wonder about why society has become just like this. It really is just depressing :(. I’m gonna go consume a beer and loosen up right now! i’m sorry if i got anyone down.

  7. Very good written information. It will be supportive to everyone who employess it, as well as myself. Keep doing what you are doing – can’r wait to read more posts.

  8. Excellent goods from you, man. I have understand your stuff previous to and you are just too magnificent. I really like what you have acquired here, certainly like what you’re saying and the way in which you say it. You make it enjoyable and you still care for to keep it smart. I can’t wait to read much more from you. This is actually a great website.

  9. Magnificent goods from you, man. I have understand your stuff previous to and you are just extremely fantastic. I really like what you’ve acquired here, certainly like what you are stating and the way in which you say it. You make it enjoyable and you still take care of to keep it smart. I can’t wait to read far more from you. This is actually a wonderful web site.

  10. Excellent beat ! I would like to apprentice while you amend your site, how can i subscribe for a blog website? The account helped me a acceptable deal. I had been tiny bit acquainted of this your broadcast offered bright clear idea

  11. Hello there, just became aware of your blog through Google, and found that it is really informative. I’m going to watch out for brussels. I will be grateful if you continue this in future. Numerous people will be benefited from your writing. Cheers!

  12. Hi there, I discovered your website by the use of Google whilst looking for a comparable matter, your site came up, it seems to be great. I have bookmarked it in my google bookmarks.

  13. Simply want to say your article is as surprising. The clearness in your post is simply spectacular and i could assume you’re an expert on this subject. Well with your permission let me to grab your feed to keep updated with forthcoming post. Thanks a million and please continue the enjoyable work.

  14. Howdy! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

  15. hey there and thank you for your information – I have definitely picked up something new from right here. I did however expertise some technical issues using this website, as I experienced to reload the site many times previous to I could get it to load correctly. I had been wondering if your web host is OK? Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage your quality score if ads and marketing with Adwords. Well I’m adding this RSS to my email and can look out for a lot more of your respective fascinating content. Ensure that you update this again soon..

  16. Simply desire to say your article is as astonishing. The clarity in your post is simply cool and i could assume you’re an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please continue the gratifying work.

  17. With amzing grace! Just fanciful! Your composition manner is admirable and the way you covered the subject with grace is notable. I am intrigued, I assume you may be an authority during this matter. I’m subscribing for your forthcoming revisions from now on.

  18. Thanks for sharing excellent informations. Your web site is very cool. I am impressed by the details that you’ve on this blog. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for extra articles. You, my friend, ROCK! I found just the information I already searched all over the place and just could not come across. What a great web-site.

closed