Tuesday, 13 December 2016

Read Office365 Outlook email also save attachement

I have one requirement to read office365 email and it is not possible using pop3Client so i have used Microsoft.Exchange.WebServices


Below are the configuration add into app.config file.
 <add key="Username" value=""/>
    <add key="Password" value=""/>
    <add key="Domain" value=""/>
    <add key="EWSUrl" value="https://outlook.office365.com/EWS/Exchange.asmx"/>
    <add key="SharedMailBox" value=""/>


Below are the codes 



Services.cs Class

   public static ExchangeService ConnectToService()
        {
            // We use this to get the target Exchange version. 
            UserData data = new UserData();
            ExchangeService service = new ExchangeService(data.Version);
            service.Url = new Uri(Convert.ToString(ConfigurationManager.AppSettings["EWSUrl"]));
            try
            {
                AuthenticationHelper.Authenticate(data.EmailAddress, data.Password, ref service);
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog(ex, AppSetting.ErrorFilePath);
            }
            return service;
        }



In Program.cs call first call ConnectToService function then call below  GetMailsFromServices function.


 public static ExchangeService GetMailsFromServices(ExchangeService service)
        {
            try
            {
                string curpath = Directory.GetCurrentDirectory();
                string mailbox = String.Format("{0}\\inbox", curpath);

                int offset = 0;
                int pageSize = 50;
              
                List<EmailMessage> emails = new List<EmailMessage>();
                ItemView view = new ItemView(pageSize, offset, OffsetBasePoint.Beginning);

                view.PropertySet = new PropertySet(ItemSchema.Flag, ItemSchema.Id, ItemSchema.Categories, ItemSchema.Attachments, FolderSchema.DisplayName);
                FolderView Folderview = new FolderView(int.MaxValue);

             
                Mailbox sharedMailbox = new Mailbox(ConfigurationManager.AppSettings["SharedMailBox"]);
                FindFoldersResults findResultsFolder = service.FindFolders(new FolderId(WellKnownFolderName.MsgFolderRoot, sharedMailbox), Folderview);
                foreach (Microsoft.Exchange.WebServices.Data.Folder folder in findResultsFolder.Folders)
                {
                    // Here we are using spacific forlder to manipulate 
                    // On the mailbox there is a rule to move all mail to "UnprocessedEmails" and processed mail to inbox 
                    if (folder.DisplayName == "Inbox")
                    {
                        ItemView itemView = new ItemView(int.MaxValue);
                        FindItemsResults<Item> searchResults = service.FindItems(folder.Id, itemView);

                   
                            foreach (var item in searchResults.Items)
                            {
                                // get the subject 
                                var senderSubject = item.Subject;
                                var fromAddress = ((EmailMessage)item).From.Address;
                                DateTime receviedDate = item.DateTimeReceived;
                                DateTime currentDate = DateTime.Now.AddDays(LastDaysToReadEmail).Date;

                                if (!string.IsNullOrWhiteSpace(senderSubject))
                                {
                                    if (senderSubject.IndexOf(EmailSubject) > 0)
                                   {
                                        emails.Add((EmailMessage)item);
                                        item.Load();
                                        if (item.HasAttachments)
                                        {
                                            foreach (var excelattachment in item.Attachments)
                                            {

                                                FileAttachment fileAttachment = excelattachment as FileAttachment;

                                                string fileExtension = Path.GetExtension(((Microsoft.Exchange.WebServices.Data.Attachment)(fileAttachment)).Name);
                                                string fileName = Path.GetFileName(((Microsoft.Exchange.WebServices.Data.Attachment)(fileAttachment)).Name);
                                                string fullPath = mailbox + "\\" + fileName;
                                                if (fileExtension == ".xls" || fileExtension == ".xlsx")
                                                {
                                                    if (!Directory.Exists(mailbox))
                                                    {
                                                        Directory.CreateDirectory(mailbox);
                                                    }

                                                    fileAttachment.Load(fullPath);
                                                    
                                                }
                                            }
                                        }
                                    }
                                }

                                if (currentDate >= receviedDate.Date)
                                {
                                    break;
                                }
                            }
                        
              
                      
                    }
                }


                return service;

            }
            catch (Exception ex)
            {
                Log.WriteErrorLog(ex, AppSetting.ErrorFilePath);
                return null;
            }
        }

Let me know if want more details about it.

No comments:

Post a Comment