Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to Programmatically Create & Open a new Outlook Email

I have a winforms application and I am trying to create a method that will create and open a new Outlook Email. So far I have

private void CreateOutlookEmail()
    {
        try
        {                
            Outlook.MailItem mailItem = (Outlook.MailItem)
                this.CreateItem(Outlook.OlItemType.olMailItem);
            mailItem.Subject = "This is the subject";
            mailItem.To = "[email protected]";
            mailItem.Body = "This is the message.";
            mailItem.Importance = Outlook.OlImportance.olImportanceLow;
            mailItem.Display(false);
        }
        catch (Exception eX)
        {
            throw new Exception("cDocument: Error occurred trying to Create an Outlook Email"
                                + Environment.NewLine + eX.Message);
        }
    }

But the 'CreateItem' reference is underlined with the error message

"does not contain a definition for CreateItem"

I thought 'CreateItem' was a standard method for MS Office items, but admittedly I did find the above code on another website and simply copied it.

What am I misunderstanding please?

like image 588
PJW Avatar asked Jun 28 '12 10:06

PJW


3 Answers

Think about it. You are calling the CreateItem method on this current object. Have you defined the CreateItem method in this class?

Instead of your:

Outlook.MailItem mailItem = (Outlook.MailItem) this.CreateItem(Outlook.OlItemType.olMailItem);

You need the lines:

Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = (Outlook.MailItem) outlookApp.CreateItem(Outlook.OlItemType.olMailItem);

You create an instance of the outlook application, on which you can call the CreateItem method.

Edit

There are two more things to make this work properly.

1) Add a reference to the Microsoft.Office.Interop.Outlook package to your project

2) Ensure you have the appropriate using statement in your class

using Outlook = Microsoft.Office.Interop.Outlook;
like image 172
luketorjussen Avatar answered Nov 08 '22 13:11

luketorjussen


Try this

string subject = "My subject";
string emailTag = string.Format("mailto:[email protected]?subject={0}", subject);
System.Diagnostics.Process.Start(emailTag);
like image 32
JohnnBlade Avatar answered Nov 08 '22 15:11

JohnnBlade


In my experience Office.Interop can be troublesome and simply kicking off Outlook with the appropriate arguments may represent a simpler and more portable option:

System.Diagnostics.Process.Start("C:\\Program Files (x86)\\Microsoft Office\\Office12\\OUTLOOK.EXE", "/c ipm.note /m [email protected]"));

Outlook command line switches give you many more options with numerous sources of info (try http://www.outlook-tips.net/how-to/using-outlook-command-lines)

like image 6
user3805384 Avatar answered Nov 08 '22 13:11

user3805384