【发布时间】:2018-03-10 20:57:58
【问题描述】:
如何使用 c# 访问 Outlook 帐户收件箱?我尝试使用 Outlook 对象模型和 imap,但它只显示登录到我的机器的 Outlook 帐户。我尝试使用其用户名和密码登录到另一个帐户,但它仍然登录到我的本地计算机帐户。我读到注销并关闭 Outlook 应该可以解决这个问题,但它并没有改变结果
这里是代码
using System;
using System.Reflection;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace ConsoleApplication1
{
public class Class1
{
public static int Main(string[] args)
{
try
{
Outlook.Application oApp = new Outlook.Application();
// Get the MAPI namespace.
Outlook.NameSpace oNS = oApp.GetNamespace("MAPI");
oNS.Logon("email address placeholder", "password placeholder", false, true);
//Get the Inbox folder.
Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
String user = oNS.CurrentUser.EntryID;
//Get the Items collection in the Inbox folder.
Outlook.Items oItems = oInbox.Items;
Console.WriteLine(oItems.Count);
Outlook.MailItem oMsg = (Outlook.MailItem)oItems.GetFirst();
Console.WriteLine(oMsg.Subject);
Console.WriteLine(oMsg.SenderName);
Console.WriteLine(oMsg.ReceivedTime);
Console.WriteLine(oMsg.Body);
int AttachCnt = oMsg.Attachments.Count;
Console.WriteLine("Attachments: " + AttachCnt.ToString());
if (AttachCnt > 0)
{
for (int i = 1; i <= AttachCnt; i++)
Console.WriteLine(i.ToString() + "-" + oMsg.Attachments[i].DisplayName);
}
for (int i = 0; i < oItems.Count; i++)
{
if (oItems.GetNext() is Outlook.MailItem)
{
oMsg = (Outlook.MailItem)oItems.GetNext();
Console.WriteLine(oMsg.Subject);
Console.WriteLine(oMsg.SenderName);
Console.WriteLine(oMsg.ReceivedTime);
Console.WriteLine(oMsg.Body);
AttachCnt = oMsg.Attachments.Count;
if (AttachCnt > 0)
{
for (int j = 1; j <= AttachCnt; j++)
Console.WriteLine(j.ToString() + "-" + oMsg.Attachments[j].DisplayName);
}
Console.WriteLine("Attachments: " + AttachCnt.ToString());
Console.WriteLine("CURRENT EMAIL # IS: " + i);
}
else
{
oItems.GetNext();
Console.WriteLine("NOT AN EMAIL");
Console.WriteLine("CURRENT EMAIL # IS: " + i);
}
}
oNS.Logoff();
oMsg = null;
oItems = null;
oInbox = null;
oNS = null;
oApp = null;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught: ", e);
}
return 0;
}
}
}
【问题讨论】:
-
显示您尝试过的代码的最小版本以及该代码的结果。
-
该帐户是否已添加到 Outlook?
-
是的,我尝试将不同的帐户添加到 Outlook,但它仍然发送到我的主要电子邮件地址。我正在使用 .Logon 函数,但我不确定是否为用户名的参数设置了正确的格式。是电子邮件地址本身还是其他?此外,代码究竟如何与 Outlook 应用程序交互以确定用户是谁?我需要在 Outlook 端做任何事情来允许访问收件箱吗?
标签: c# email outlook imap inbox