Search code examples
c#apioffice365email-attachmentsemail-client

Having issues saving email attachment to directory


I am working on an application that crawls my email and sniffs out any emails with attachments. All attachment are being returned in the order they were received. Now I want to go a step further and would like to save any attachments in a local directory. I have been looking for documentation or examples but I have come up empty. I will show you a snippet of my code

This Function will get Email Attachments

public static List<IMessage> GetEmailAttachments()
    {
        OutlookServicesClient star_Mail_Box = Start_OutLook_Services();

        try
        {

            var Email_Box = star_Mail_Box.Users["*****@dell.com"].Folders["Inbox"].Messages.Where(m => m.HasAttachments == true).Expand(m => m.Attachments).ExecuteAsync();

            var messages = Email_Box.Result.CurrentPage;

            foreach (var message in messages.OrderByDescending(m=> m.DateTimeReceived))
            {
                var attachments = message.Attachments.CurrentPage;

                foreach (var attachment in attachments)
                {
                  ///This is where I will need to put my Logic.                       
                }
            }
        }

        catch (Exception ex)
        {
            Console.WriteLine("Not Able To Get This Mail Box" + ex.Message + "\n\nDetails : \n\n " + ex.InnerException);
            Console.ReadLine();

        }

        return null; // returning null right now for testing 
    }

Solution

  • Ok so after looking at the attachment definition I figured I go through a byte array to achieve what I want. Here goes the Some code for my attachment loop.

    foreach (FileAttachment attachment in attachments)
    {
        byte[] bytefiles = attachment.ContentBytes;
        string path = @"C:\Top-Level\" + attachment.Name;
    
        if (!string.IsNullOrEmpty(message.Subject))
        {
            path =  @"C:\Top-Level\" + message.Subject + "." + attachment.ContentType;
        }
        File.WriteAllBytes(path, bytefiles);
    }