Creating an Outlook Message File with C#

NOTE: Image attachments and file attachments had been removed as the resources are no longer available. I am in the process of reserrecting this blog. Looking forward to contribute back to the community again. =)


I've been working with a government agency lately, and came to notice that the software system they're using dates back to the stone ages. Many a time, the head of department is required to send an email to other head of departments within the same organization, each with a similar content, yet with attachment of nominal roll of folks under each of the departments (PS: HR Stuff).

On every occasion that I observe, this poor balding guy has to create a template in outlook and copy it 20 times, adding the list of recipients to the individual MSG file and attaching the relevant set of excel/word document file for each of these departments.

Of course, as a software engineer, the first thing on the mind is definitely, "AUTOMATION"!

Microsoft Office Outlook does have an interop dll which specifically allows for this to be done, easily! Another altanative would definitely be making use of Visual Studio Tools for Office (VSTO).

To save you the trouble of looking for this DLL, i've attached a copy to this blogpost.

1. To begin, let's first create a C# Winforms Project in Visual Studio.

2. Next, let's add the reference to the interop DLL (attached on this blog post). You should see something like the following.

3. For the purpose of this tutorial, we'd create a simple windows form which takes in the mail receipient, subject, message and attachment fields. Once you're familiar with how the code (which we'd discuss later), you can work more magic around this (e.g. creating automation processes)

Note: The Importance ComboBox should have the following values "High","Normal" and 'Low".

4. Next step, is to wire up the code-behind for the Save Button. It's optional whether you want to register the Outlook Interop in the namespace or not. In this example, I do not so so, thus qualifying the full path in the code (below).

// Creates a new Outlook Application Instance
Outlook.Application objOutlook = new Outlook.Application();

// Creating a new Outlook Message from the Outlook Application Instance
Outlook.MailItem mic = (Outlook.MailItem)(objOutlook.CreateItem(Outlook.OlItemType.olMailItem));

// Assigns the "TO", "CC" and "BCC" Fields
mic.To = toTextBox.Text;
mic.CC = ccTextBox.Text;
mic.BCC = bccTextBox.Text;

// Assigns the Subject Field

mic.Subject = subjectTextBox.Text;// Switch the Importance ComboBox to identify the Mail Message Importance Level
switch (importanceComboBox.SelectedItem.ToString())
{
        case "High":
                mic.Importance = Outlook.OlImportance.olImportanceHigh;
                break;         case "Normal":
                mic.Importance = Outlook.OlImportance.olImportanceNormal;
                break;



        case "Low":
                mic.Importance = Outlook.OlImportance.olImportanceLow;
                break;
}

// Define the Mail Message Body. In this example, you can add in HTML content to the mail message body

mic.HTMLBody = messageTextBox.Text;

// Adds Attachment to the Mail Message. 
// Note: You could add more than one attachment to the mail message. 
// All you need to do is to declare this relative to the number of attachments you have.

mic.Attachments.Add(attachmentOneTextBox.Text,Outlook.OlAttachmentType.olByValue,1,"Attachment Name");

// Save the message to C:\demo.msg. Alternatively you can create a SaveFileDialog to 
// allow users to choose where to save the file

mic.SaveAs(@"C:\demo.msg", Outlook.OlSaveAsType.olMSG);

Easy isn't it? Besides creating mail messages, you can also create other outlook items such as task, calendar objects and more. More to come in the future posts. Do let me know your comments/views on this post.

18 Comments

  • I'm in need of a solution that does not require Outlook to be installed on the machine, in order to create the msg file... You wouldn't happen to if that's possible? :)

  • All you would need to use is the Interop.Outlook DLL for the creation of the .MSG file.

  • U have not told any thing about pasting pic in body and sending as email..

  • Hi,
    You still need outlook on computer, which try create msg file, try it on clean computer without outlook and exception occured

  • If Outlook is already open, can I use that instances instead of creating a new Outlook.Application ?

  • Hi Petr Snobelt,

    Even when you had then Interop.DLL imported and referenced too?

  • Hi aaaa,

    I've not been able to post images into a HTML mail unless its in Rich-Text format. The best that I got to using HTML was to post attachments of the images.

  • I was trying to send attachment, but i was not able to do so. After going through this code i tried and i got success. This is really helpful for the guys like me :)

  • Try Aspose, if you need to create/parse outlook msg files without Office Outlook installation and outlook.interop.dll. Its purely written in .NET. Check out http://www.aspose.com/documentation/file-format-components/aspose.network-for-.net/creatingsaving-outlook-message-msg-files.html for sample code.

  • Excellent article, dug me out of a pickle.

    Thanks for sharing.

    TB

  • Thanks for this article Darren, it dug me out of a hole.

    This code creates a new MSG. Is there a way to create an MSG that has the same properties as a sent MSG? I'm trying to recreate a sent email from a HTML archived version. Also do you know of any tricks to modify the SentDate?

    Thanks,
    Tom

  • thanks a lot. it worked form me.

  • Darren,

    This is just what I was looking for as an intro the the interop code, although I have the same question as Tom above, which is do you know how to make a "sent" .msg which opens up in a non-editable window?

    Ta,

    Steve

  • hi.i would like to add an outlook feature on an asp.net project that iam doing,tried workink with this code but did'nt work...when i click on a button ,an outlook application must popout

  • Thanks! It's very useful!

  • Hi,
    I wrote C# application for import unread e-mails from outlook 2007, I could import sender name, sender mail address,subject and body to data grid view as following

    foreach (Microsoft.Office.Interop.Outlook._MailItem mailItem in fldEmails.Items)
    {
    if (mailItem.UnRead)
    {

    UnreadEmails mail = new UnreadEmails();

    // mail.AttachmentContent = (mailItem.UnRead == false) ? string.Empty : mailItem.Attachments.Session.OpenSharedItem;

    foreach (Microsoft.Office.Interop.Outlook.Attachment Atmt in mailItem.Attachments)
    {
    mail.AttachmentContent = (mailItem.UnRead == false) ? string.Empty : Atmt.DisplayName;
    }

    emails.Add(mail);

    }


    }


    UnreadEmails is a separate class. but couldn't find a way to import attachments (word, pdf, ppt, excel) because I need it for my filter pls help me about it


    but I could import inly name of the attachment but I need to import attachment content (word, pdf , ppt .. etc. ) to this data grid pls tell how I can do it ... with the code

  • Hi, I tried this sample and I have a problem with it. Instead mic.SaveAs I wrote mic.Display() and I'm not able to open any attached file in the outlook window. Do you know why?

  • Good article. "Poor balding guy" comment did not add much value to the material. LOL

Comments have been disabled for this content.