I want to use send emails via Outlook as described here. It works fine as long as I have already opened Outlook. So for example if Outlook is minimized and I execute my code, then I can send an email just fine. But if Outlook is closed, then I get an exception:
{System.Runtime.InteropServices.COMException (0x80004004): Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))
at Microsoft.Office.Interop.Outlook._MailItem.get_Recipients()
at OutlookExample.Form1.btnSendEmail_Click(Object sender, EventArgs e) in C:UsersabcDocumentsVisual Studio 2008ProjectsOutlookExampleOutlookExampleForm1.cs:line 28}
Here is the code:
using Outlook = Microsoft.Office.Interop.Outlook;
...
private void btnSendEmail_Click(object sender, EventArgs e)
{
try
{
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg.HTMLBody = "Hello, here is your message!";
oMsg.Subject = "This is a test message";
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("[email protected]");
oRecip.Resolve();
oMsg.Send();
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Why doesn't this work?
Edit: Here is the solution
using Outlook = Microsoft.Office.Interop.Outlook;
...
private void btnSendEmail_Click(object sender, EventArgs e)
{
try
{
Outlook.Application oApp = new Outlook.Application();
// These 3 lines solved the problem
Outlook.NameSpace ns = oApp.GetNamespace("MAPI");
Outlook.MAPIFolder f = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
System.Threading.Thread.Sleep(5000); // test
Outlook.MailItem oMsg = Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg.HTMLBody = "Hello, here is your message!";
oMsg.Subject = "This is a test message";
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("[email protected]");
oRecip.Resolve();
oMsg.Send();
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…