Tuesday, 13 December 2016

Read email of outlook of pop3 server

when you read email if your server is pop3 server.


using (Pop3Client client = new Pop3Client())
                {

                    // Connect to the server
                    client.Connect(EmailServer, Convert.ToInt32(Port), true);

                    // Authenticate ourselves towards the server
                    client.Authenticate(UserName, Password);

                    // Get the number of messages in the inbox
                    int messageCount = client.GetMessageCount();

                    List<Email> Emails = new List<Email>();
                    int counter = 0;
                    for (int i = messageCount; i >= 1; i--)
                    {
                        DateTime currentDate = DateTime.Now.AddDays(-2).Date;

                        Message message = client.GetMessage(i);
                        Email email = new Email()
                        {
                            MessageNumber = i,
                            Subject = message.Headers.Subject,
                            DateSent = message.Headers.Date,
                            From = message.Headers.From.Address,
                        };

                     
                            MessagePart body = message.FindFirstHtmlVersion();
                            if (body != null)
                            {
                                email.Body = body.GetBodyAsText();
                            }
                            else
                            {
                                body = message.FindFirstPlainTextVersion();
                                if (body != null)
                                {
                                    email.Body = body.GetBodyAsText();
                                }
                            }
                            List<MessagePart> attachments = message.FindAllAttachments();

                            foreach (MessagePart attachment in attachments)
                            {
                                email.Attachments.Add(new Attachment
                                {
                                    FileName = attachment.FileName,
                                    ContentType = attachment.ContentType.MediaType,
                                    Content = attachment.Body
                                });
                                string filePath = mailbox + "\\" + attachment.FileName;
                                if (Path.GetExtension(filePath) == ".xlsx" || Path.GetExtension(filePath) == ".xls")
                                {
                                    FileStream Stream = new FileStream(filePath, FileMode.Create);
                                    Stream.Position = 0;
                                    BinaryWriter BinaryStream = new BinaryWriter(Stream);
                                    BinaryStream.Write(attachment.Body);
                                    Stream.Close();
                                    BinaryStream.Close();
                                }
                            }


                            Emails.Add(email);
                        }
                        counter++;
                        if (currentDate >= Convert.ToDateTime(email.DateSent).Date)
                        {
                            break;
                        }
                 

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.