我開發的方法可以成功地將電子郵件附件下載到本地PC。
我也必須直接從郵件下載到ftp服務器。
我試圖實現我認爲應該工作的功能。
當我成功獲得FileAttachment對象時,我嘗試使用其屬性ContentLocation來獲取附件URL
然後我將該URL傳遞給webClient.DownloadString()方法。
但不幸的是,屬性ContentLocation始終爲空。
所以我在這行代碼中有一個異常。
這裏是我的意見的方式完整列表:將附件從電子郵件直接下載到FTP服務器
var service = new ExchangeService(ExchangeVersion.Exchange2013);
service.Credentials = new NetworkCredential(serviceUserName, servicePassword);
service.Url = new Uri(serviceUrl);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
var path = System.IO.Directory.CreateDirectory(Path.Combine(applicationPath, name));
//Filters
List<SearchFilter> searchANDFilterCollection = new List<SearchFilter>();
searchANDFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
searchANDFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.From, new EmailAddress(email)));
SearchFilter sf =
new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchANDFilterCollection.ToArray());
FindItemsResults<Item> findResults;
ItemView view = new ItemView(10);
do
{
findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
if (findResults != null && findResults.Items != null && findResults.Items.Count > 0)
foreach (EmailMessage item in findResults)
{
var message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
foreach (Attachment attachment in message.Attachments)
{
if (attachment is FileAttachment)
{
if (attachment.Name.Contains(".xlsx") || attachment.Name.Contains(".xlsb") || attachment.Name.Contains(".xls") || attachment.Name.Contains(".csv"))
{
var fileAttachment = attachment as FileAttachment;
//Download to ftp
if (isSaveToFTP)
{
var webClient = new WebClient();
string readHtml = webClient.DownloadString(fileAttachment.ContentLocation);
byte[] buffer = Encoding.Default.GetBytes(readHtml);
WebRequest makeDirectory = WebRequest.Create(Path.Combine(ftpAddress, name));
makeDirectory.Method = WebRequestMethods.Ftp.MakeDirectory;
makeDirectory.Credentials = new NetworkCredential(username, password);
WebRequest uploadFile = WebRequest.Create(ftpAddress + name + "/" + fileAttachment.Name);
uploadFile.Method = WebRequestMethods.Ftp.UploadFile;
uploadFile.Credentials = new NetworkCredential(username, password);
Stream reqStream = uploadFile.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
}
//Download to pc
else fileAttachment.Load(String.Format(@"{0}\{1}", path, fileAttachment.Name));
}
}
//fileAttachment.Load(path.Name);
}
}
// mark email as read
item.IsRead = true;
item.Update(ConflictResolutionMode.AlwaysOverwrite);
}
}
while (findResults.MoreAvailable);
我應該改變,以得到這個工作?
或者還有其他解決方案嗎?
謝謝你,它的工作原理 –