簡體   English   中英

從服務器檢索電子郵件附件

[英]Retrieving email attachments from server

我們會定期發送一封電子郵件(請求將由用戶驅動),其中包含一個Excel附件。 目的是自動從電子郵件中提取附件,並將其傳遞給將處理文件中數據的方法。

我想遠離第3方工具或庫,並且我想使其盡可能簡單,最少的檢查和功能,只要電子郵件地址與已知來源相匹配,就可以直接下載郵件,保存附件。 (阻止垃圾郵件)。

從研究來看,有3種可能的解決方案。 哪一條是最明智的路線? 還有其他選擇嗎? 有人可以指出我相關的(和最新的)教程嗎?

  • 使用第三方POP客戶端下載
  • 編寫我自己的功能,可能使用Exchange EWS(首選)(使用C#,VS2010)
  • 而是讓Outlook下載它,然后從Outlook中提取附件

這是我如何使用我們的系統的示例。 如果您要我解釋任何事情,請告訴我,因為我確實必須盡快發布此內容。

namespace Namespace.Email
{
    public class EmailLinker
    {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);

        public EmailLinker()
        {
            service.Credentials = new NetworkCredential("username", "password", "domain");
            service.AutodiscoverUrl("email@email.com");
        }

        public void linkEmails()
        {
            FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(128));
            if (findResults.TotalCount > 0)
            {
                ServiceResponseCollection<GetItemResponse> items = service.BindToItems(findResults.Select(item => item.Id), new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.ToRecipients));

                foreach (GetItemResponse i in items)
                {
                    MailItem m = new MailItem();
                    Item it = i.Item;
                    m.From = ((Microsoft.Exchange.WebServices.Data.EmailAddress)it[EmailMessageSchema.From]).Address;
                    m.Recipients = ((Microsoft.Exchange.WebServices.Data.EmailAddressCollection)it[EmailMessageSchema.ToRecipients]).Select(r => r.Address).ToArray();
                    m.Subject = it.Subject;
                    m.Body = it.Body.Text;
                    m.Recieved = it.DateTimeReceived;
                    m.attachments = it.Attachments;
                    foreach (Attachment a in m.attachments)
                         this.uploadAttachments(a);
                    i.Item.Delete(DeleteMode.HardDelete);
                }
            }
        }

        private void uploadAttachments(Attachment a)
        {
            ContentFile cf = new ContentFile();
            cf.Name = a.Name;
            cf.Size = a.Size;
            cf.ContentType = MimeTypeMap.GetMimeType(Path.GetExtension(a.Name).Replace(".",""));
            FileAttachment fa = (FileAttachment)a;
            fa.Load();
            cf.Data = fa.Content;
            cf.DateAdded = DateTime.Now;
            cf.save();
        }

        public class MailItem
        {
            public int id;
            public string From;
            public string[] Recipients;
            public string Subject;
            public string Body;
            public DateTime Recieved;
            public string RecievedString
            {
                get
                {
                    return Recieved.ToShortDateString() + " " + Recieved.ToShortTimeString();
                }
            }
            public AttachmentCollection attachments;
        }
    }
}
public class KCSExchangeLink : IKCSExchangeLink
{

    private 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;
        }
    }

    private 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;
    }

    public void SaveAttachment(string email, string password, string downloadfolder, string fromaddress)
    {
        ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
        service.Credentials = new WebCredentials(email, password);
        service.TraceEnabled = true;
        service.TraceFlags = TraceFlags.All;
        service.AutodiscoverUrl(email, RedirectionUrlValidationCallback);

        // Bind the Inbox folder to the service object.
        Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);

        // The search filter to get unread email.
        SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
        ItemView view = new ItemView(1);

        // Fire the query for the unread items.
        // This method call results in a FindItem call to EWS.
        FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);

        foreach (EmailMessage item in findResults)
        {
            item.Load();

            /* download attachment if any */
            if (item.HasAttachments && item.Attachments[0] is FileAttachment && item.From.Address == fromaddress)
            {
                FileAttachment fileAttachment = item.Attachments[0] as FileAttachment;

                /* download attachment to folder */
                fileAttachment.Load(downloadfolder + fileAttachment.Name);
            }

            /* mark email as read */
            item.IsRead = true;
            item.Update(ConflictResolutionMode.AlwaysOverwrite);
        }

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM