【发布时间】:2020-07-13 22:26:12
【问题描述】:
我编写了一个 .Net c# 控制台应用程序,用于从具有特定凭据的 Office365 邮箱中提取电子邮件。 这个应用程序在我的开发 PC 上完美运行。我现在需要将它部署到 Windows 服务器(2019)并通过作业调度程序运行。但是在服务器上它不起作用,我得到“找不到自动发现服务”。错误。 请看我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Exchange.WebServices.Data;
using System.Configuration;
using System.Globalization;
using System.IO;
namespace DWMailProcessor
{
class Program
{
static void Main(string[] args)
{
string emailName = ConfigurationManager.AppSettings["emailName"];
string emailPassWord = ConfigurationManager.AppSettings["emailPassWord"];
string filterSubject = ConfigurationManager.AppSettings["filterSubject"];
string extractFilePath = ConfigurationManager.AppSettings["extractFilePath"];
string emailFolder = ConfigurationManager.AppSettings["emailFolder"];
string logFilePath = ConfigurationManager.AppSettings["logFilePath"] + $@"\DWMailProcessor.ErrorLog"; ;
try
{
ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
exchange.Credentials = new WebCredentials(emailName, emailPassWord);
exchange.AutodiscoverUrl(emailName, RedirectionUrlValidationCallback);
if (exchange != null)
{
Folder rootFolder = Folder.Bind(exchange, WellKnownFolderName.MsgFolderRoot);
SearchFilter ff = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, emailFolder);
FindFoldersResults fresult = rootFolder.FindFolders(ff, new FolderView(1));
FindItemsResults<Item> result;
do
{
SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, filterSubject);
result = exchange.FindItems(WellKnownFolderName.Inbox, sf, new ItemView(100));
foreach (Item item in result)
{
EmailMessage message = EmailMessage.Bind(exchange, item.Id);
FileAttachment attachment = (FileAttachment)message.Attachments[0];
attachment.Load(extractFilePath + @"\" + attachment.Name);
item.Move(fresult.Folders[0].Id);
}
} while (result.TotalCount > 0);
}
}
catch (Exception e)
{
using (StreamWriter sw = new StreamWriter(logFilePath, append: true))
{
sw.WriteLine($"Fatal[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InstalledUICulture)}]: {e.Message}");
}
//throw;
return;
}
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
}
}
注意:所有凭据均从 App.Config 文件中获取 我在服务器上只有有限的权限,我们的 IT 对如何解决这个问题没有太多的线索。 这可能是防火墙问题吗?因为服务器仅限于互联网。即(只有特定的 url 和端口是开放的。IT 说他们打开了https://outlook.office365.com/EWS/Exchange.asmx) 使用 EWS API 需要哪些防火墙规则(如果有)?有没有其他方法可以从服务器解决此问题?
提前非常感谢。
【问题讨论】: