1

We have an email coming at regular intervals (the request will be user driven), containing an Excel attachment. The goal is to extract the attachment from the email automatically, and pass it on to the method that will deal with the data in the file.

I'd like to stay away from 3rd party tools or libraries, and I'd like to keep this as simple as possible, minimal checks and features, literally just download the mail, save the attachment, if the email address matches the known source (to block spam).

From researching, there are 3 possible solutions. Which would be the most sensible route? And are there other options? Can anybody point me to relevant (and recent) tutorials?

  • Download using a 3rd party POP client
  • Write my own functionality, possibly using Exchange EWS (Preferred option) (using C#, VS2010)
  • Rather have Outlook download it, and then extract the attachment from Outlook
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0

Here is an example of how I do it with our system. Let me know if you want me to explain anything as I did have to post this pretty quick.

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;
        }
    }
}
nwestfall
  • 219
  • 2
  • 5
  • 13
0
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);
        }

    }

}