How to: Create a Mail Item Using a Message Template

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

This example creates a mail item by using the CreateItemFromTemplate method.

Example

This code sample opens the Ivy.oft template file, assigns a subject, and then saves the message to the Drafts folder.

The CreateItemFromTemplate method is useful if you have an Outlook form template file (.oft) stored on disk that you want to use as a message template. The template file can contain preformatted text, stationery, or images that you want to include in the message. However, if the template file contains code behind the form, the form code will not run.

If you use Microsoft Visual Studio to test this code sample, you must first add a reference to the Microsoft Outlook 12.0 Object Library component and specify the Outlook variable when you import the Microsoft.Office.Interop.Outlook namespace. The Imports or using statements must not occur right before the functions in the Code section but must be added before the public Class declaration. The following lines of code show how to do the import and assignment in Visual Basic and in C#:

Imports Outlook = Microsoft.Office.Interop.Outlook
using Outlook = Microsoft.Office.Interop.Outlook;
Private Sub CreateItemFromTemplate()
    Dim folder As Outlook.Folder = _
        CType(Application.Session.GetDefaultFolder( _
        Outlook.OlDefaultFolders.olFolderDrafts), Outlook.Folder)
    Dim mail As Outlook.MailItem = _
        CType(Application.CreateItemFromTemplate( _
        "c:\ivy.oft", folder), Outlook.MailItem)
    mail.Subject = "Congratulations"
    mail.Save()
End Sub
private void CreateItemFromTemplate()
{
    Outlook.Folder folder =
        Application.Session.GetDefaultFolder(
        Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder;
    Outlook.MailItem mail =
        Application.CreateItemFromTemplate(
        @"c:\ivy.oft", folder) as Outlook.MailItem;
    mail.Subject = "Congratulations";
    mail.Save();
}