【问题标题】:Office365 read Inbox email in C#Office365 在 C# 中读取收件箱电子邮件
【发布时间】:2019-02-21 12:45:16
【问题描述】:

遇到错误

Microsoft.Exchange.WebServices.dll 中出现“Microsoft.Exchange.WebServices.Data.AutodiscoverLocalException”类型的未处理异常

ExchangeService oews = new ExchangeService(ExchangeVersion.Exchange2013_SP1)
            {
                Credentials = new WebCredentials("mohanb@cubicsp.onmicrosoft.com","******") //state your Exchange username,Exchange Password and Exchange Domain
            };
            oews.AutodiscoverUrl("mohanb@cubicsp.onmicrosoft.com");     //User Mailbox whose inbox is to be accessed.
            FindFoldersResults foundFolderResults = oews.FindFolders(WellKnownFolderName.Inbox, new FolderView(int.MaxValue));
            MEWS.Folder exchangeExchangeAPIArchivedFolder = foundFolderResults.Folders.ToList().Find(
                f => f.DisplayName.Equals("SentItem", StringComparison.CurrentCultureIgnoreCase));

我在此处使用 https://outlook.office365.com/EWS/Exchange.asmx 更改了代码 现在我收到此错误

Microsoft.Exchange.WebServices.dll 中出现“Microsoft.Exchange.WebServices.Data.ServiceRequestException”类型的未处理异常

附加信息:请求失败。远程服务器返回错误:(401) Unauthorized.

ExchangeService _service = new ExchangeService();
            _service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

            foreach (EmailMessage email in _service.FindItems(WellKnownFolderName.Inbox, new ItemView(10))) {

                email.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.TextBody));
                string recipients = "";

                foreach (EmailAddress emailAddress in email.CcRecipients)
                {
                    recipients += ";" + emailAddress.Address.ToString();
                }
                string internetMessageId = email.InternetMessageId;
                string fromAddress = email.From.Address;
                string recipient = recipients;
                string subject = email.Subject;

            }

提前致谢

【问题讨论】:

  • 你确定“mohanb@cubicsp.sharepoint.com”是邮箱地址吗?你试过“mohanb@cubicsp.onmicrosoft.com”吗?
  • 感谢 Dmitry,我错误地粘贴了电子邮件地址,但更改后仍然出现同样的错误。

标签: outlook office365


【解决方案1】:

这可能是身份验证问题。

您可以添加以下代码:

service.PreAuthenticate = true;

service.Credentials = new WebCredentials("YouEmailAdress","Password");

这是完整的代码:

ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
            //ICredentials creds = new NetworkCredential("xxxx", "xxxx.com");
            service.Credentials = new WebCredentials("YouEmailAdress","Password");
            service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
            service.PreAuthenticate = true;
            service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, " YouEmailAdress");
            ItemView view = new ItemView(int.MaxValue);
            FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, SetFilter(), view);

            foreach (Item item in findResults.Items)
            {
                if (item.Subject != null)
                {
                    list.Add(item.Subject.ToString());
                }
                else
                {
                    list.Add("test");
                }
                list.Add(item.DateTimeSent.ToString());
            }  
        }
        private static SearchFilter SetFilter()
        {
            List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
            searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
            SearchFilter s = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
            return s;
        }
        private static bool CertificateValidationCallBack(
         object sender,
         System.Security.Cryptography.X509Certificates.X509Certificate certificate,
         System.Security.Cryptography.X509Certificates.X509Chain chain,
         System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
            {
                return true;
            }

            // If there are errors in the certificate chain, look at each error to determine the cause.
            if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
            {
                if (chain != null && chain.ChainStatus != null)
                {
                    foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
                    {
                        if ((certificate.Subject == certificate.Issuer) &&
                           (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
                        {
                            // Self-signed certificates with an untrusted root are valid. 
                            continue;
                        }
                        else
                        {
                            if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
                            {
                                // If there are any other errors in the certificate chain, the certificate is invalid,
                                // so the method returns false.
                                return false;
                            }
                        }
                    }
                }

                // When processing reaches this line, the only errors in the certificate chain are 
                // untrusted root errors for self-signed certificates. These certificates are valid
                // for default Exchange server installations, so return true.
                return true;
            }
            else
            {
                // In all other cases, return false.
                return false;
            }
        }

如果您使用的帐户不是您的帐户,您需要确保我们拥有以下文章所述的 EWS 模拟所需的权限:

Configuring Exchange Impersonation (Exchange Web Services)

Using Exchange Impersonation (Exchange Web Services)

【讨论】:

  • 非常感谢 Alina,我为 office365 手动设置了模拟权限,现在可以使用了。
【解决方案2】:

401 表示您的凭据错误。

【讨论】:

  • 我交叉验证的凭据是正确的,你能确认我一件事是需要在本地桌面安装 Outlook,对于这个参考 Microsoft.Exchange.WebServices.dll,我已经使用 nuget 包管理器添加了参考.
  • EWSEditor 可以连接到那个邮箱吗?
  • 现在我可以从office365邮箱访问邮件了,我为office365手动设置了模拟权限。这个对我有用。感谢您的帮助和支持。
猜你喜欢
  • 2022-01-17
  • 2013-12-19
  • 1970-01-01
  • 2011-06-01
  • 2020-05-30
  • 1970-01-01
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多