【发布时间】:2017-04-11 12:52:55
【问题描述】:
这是我要解决的方案:我的用户“myuser”可以访问服务邮箱“serviceMail”。所以这不是我的个人邮箱,而是我公司的另一个邮箱设置,我们出于各种目的将电子邮件发送到该邮箱。我知道我可以访问它,因为我已经在我的 Outlook 中添加了这个邮箱,并且我可以像往常一样检查收件箱来查看我自己的电子邮件。我正在尝试使用 EWS 编写一个 c# 程序,该程序将从“serviceMail”收件箱中的电子邮件中获取附件。尝试查找项目时,我收到“401 未经授权的访问”。我究竟做错了什么?我的代码如下。
这是我连接到服务的方式:
public ExchangeService ConnectToExchangeServer()
{
const string strMailbox = "serviceMail@abc.com";
const string strLoginUser = "mysuer@abc.com";
const string strLogingUserpwd = "pwd";
const string strO365Url = "https://outlook.office365.com/EWS/Exchange.asmx";
try
{
exchange = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
exchange.Credentials = new WebCredentials(strLoginUser, strLogingUserpwd, "sabra.com");
// exchange.AutodiscoverUrl(strMailbox,RedirectionUrlValidationCallback);
exchange.Url = new Uri(strO365Url);
return exchange;
}
catch (Exception ex)
{
}
return exchange;
}
以下是尝试查找项目的代码
ExchangeService service = ga.ConnectToExchangeServer();
TimeSpan ts = new TimeSpan(0, -1, 0, 0);
DateTime date = DateTime.Now.Add(ts);
SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
if (service != null)
{
//FindItemsResults<Item> findResults = ga.exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));
//FindItemsResults<Item> findResults = ga.exchange.FindItems(WellKnownFolderName.Inbox,);
// Return a single item.
ItemView view = new ItemView(1);
string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email";
// Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS.
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, querystring, view);
foreach (Item item in findResults)
{
EmailMessage message = EmailMessage.Bind(ga.exchange, item.Id);
if (message.HasAttachments && message.Attachments[0] is FileAttachment)
{
FileAttachment fileAttachment = message.Attachments[0] as FileAttachment;
//Change the below Path
fileAttachment.Load(@"D:\\QlikData\\Lean\\EmailExtract" + fileAttachment.Name);
// lblAttach.Text = "Attachment Downloaded : " + fileAttachment.Name;
}
else
{
// MessageBox.Show("No Attachments found!!");
}
}
if (findResults.Items.Count <= 0)
{
//lstMsg.Items.Add("No Messages found!!");
}
}
我收到错误“请求失败。远程服务器返回错误:(401) 未经授权。”在 FindItemsResults findResults = service.FindItems(WellKnownFolderName.Inbox, querystring, view) 代码行上。
有什么想法吗?
【问题讨论】:
-
您解决了这个问题吗?我的 MacOS 也有同样的问题。