gpt4 book ai didi

c# - 如果 Outlook 打开,则只能通过 Outlook 发送电子邮件

转载 作者:可可西里 更新时间:2023-11-01 07:52:37 27 4
gpt4 key购买 nike

我想按照说明使用 Outlook 发送电子邮件 here .只要我已经打开 Outlook,它就可以正常工作。因此,例如,如果将 Outlook 最小化并执行我的代码,那么我就可以很好地发送电子邮件。但是,如果 Outlook 关闭,则会出现异常:

{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:\Users\abc\Documents\Visual Studio 2008\Projects\OutlookExample\OutlookExample\Form1.cs:line 28}

代码如下:

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("rhr@sonlinc.dk");
oRecip.Resolve();
oMsg.Send();
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

为什么这行不通?

编辑:这是解决方案

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("rhr@sonlinc.dk");
oRecip.Resolve();
oMsg.Send();
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

最佳答案

以下代码对我来说已经可靠地工作了几个月:

            app = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace ns = app.GetNamespace("MAPI");
f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Thread.Sleep(5000); // a bit of startup grace time.

如果 outlook 已打开,则使用它,如果未打开,则使用它。当然,如果您的 outlook 要求您登录,您的代码将不允许这样做。某些系统使您难以自动登录。

关于c# - 如果 Outlook 打开,则只能通过 Outlook 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11330101/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com