示例#1
1
        public void CheckMail()
        {
            try
            {
                string processLoc = dataActionsObject.getProcessingFolderLocation();
                StreamWriter st = new StreamWriter("C:\\Test\\_testings.txt");
                string emailId = "*****@*****.**";// ConfigurationManager.AppSettings["UserName"].ToString();
                if (emailId != string.Empty)
                {
                    st.WriteLine(DateTime.Now + " " + emailId);
                    st.Close();
                    ExchangeService service = new ExchangeService();
                    service.Credentials = new WebCredentials(emailId, "Sea2013");
                    service.UseDefaultCredentials = false;
                    service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                    Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
                    SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                    if (inbox.UnreadCount > 0)
                    {
                        ItemView view = new ItemView(inbox.UnreadCount);
                        FindItemsResults<Item> findResults = inbox.FindItems(sf, view);
                        PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.ToRecipients);
                        itempropertyset.RequestedBodyType = BodyType.Text;
                        //inbox.UnreadCount
                        ServiceResponseCollection<GetItemResponse> items = service.BindToItems(findResults.Select(item => item.Id), itempropertyset);
                        MailItem[] msit = getMailItem(items, service);

                        foreach (MailItem item in msit)
                        {
                            item.message.IsRead = true;
                            item.message.Update(ConflictResolutionMode.AlwaysOverwrite);
                            foreach (Attachment attachment in item.attachment)
                            {
                                if (attachment is FileAttachment)
                                {
                                    string extName = attachment.Name.Substring(attachment.Name.LastIndexOf('.'));
                                    FileAttachment fileAttachment = attachment as FileAttachment;
                                    FileStream theStream = new FileStream(processLoc + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                                    fileAttachment.Load(theStream);
                                    byte[] fileContents;
                                    MemoryStream memStream = new MemoryStream();
                                    theStream.CopyTo(memStream);
                                    fileContents = memStream.GetBuffer();
                                    theStream.Close();
                                    theStream.Dispose();
                                    Console.WriteLine("Attachment name: " + fileAttachment.Name + fileAttachment.Content + fileAttachment.ContentType + fileAttachment.Size);
                                }
                            }
                        }
                    }
                    DeleteMail(emailId);
                }
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// Dump the properties from the given PropertySet of every item in the
        /// ItemId list to XML files.
        /// </summary>
        /// <param name="itemIds">List of ItemIds to get</param>
        /// <param name="propertySet">PropertySet to use when getting items</param>
        /// <param name="destinationFolderPath">Folder to save messages to</param>
        /// <param name="service">ExchangeService to use to make EWS calls</param>
        public static void DumpXML(
            List <ItemId> itemIds,
            PropertySet propertySet,
            string destinationFolderPath,
            ExchangeService service)
        {
            DebugLog.WriteVerbose(String.Format("Getting {0} items by ItemId.", itemIds.Count));
            service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
            ServiceResponseCollection <GetItemResponse> responses = service.BindToItems(itemIds, propertySet);

            DebugLog.WriteVerbose("Finished getting items.");

            DebugLog.WriteVerbose("Started writing XML dumps to files.");
            foreach (GetItemResponse response in responses)
            {
                switch (response.Result)
                {
                case ServiceResult.Success:
                    DumpXML(response.Item, destinationFolderPath);
                    break;

                case ServiceResult.Error:
                    DumpErrorResponseXML(response, destinationFolderPath);
                    break;

                case ServiceResult.Warning:
                    throw new NotImplementedException("DumpXML doesn't handle ServiceResult.Warning.");

                default:
                    throw new NotImplementedException("Unexpected ServiceResult.");
                }
            }

            DebugLog.WriteVerbose("Finished writing XML dumps to files.");
        }
        private static void GetAllMessageEmail(Collection <ItemId> itemIds)
        {
            if (itemIds == null || itemIds.Count == 0)
            {
                return;
            }
            exchangeSecretarReport = new List <EmailMessage>();
            PropertySet propertySet = new PropertySet(EmailMessageSchema.Subject, EmailMessageSchema.ToRecipients, EmailMessageSchema.IsRead, EmailMessageSchema.Sender, EmailMessageSchema.TextBody, EmailMessageSchema.Body, EmailMessageSchema.DateTimeSent);
            ServiceResponseCollection <GetItemResponse> responses = exchangeService.BindToItems(itemIds, propertySet);

            foreach (GetItemResponse getItemResponse in responses)
            {
                try
                {
                    Item         item    = getItemResponse.Item;
                    EmailMessage message = (EmailMessage)item;
                    exchangeSecretarReport.Add(message);
                    //Console.WriteLine("Found item {0}.", message.Id.ToString().Substring(144));
                }
                catch (Exception ex)
                {
                    //Console.WriteLine("Exception while getting a message: {0}", ex.Message);
                }
            }
            if (responses.OverallResult == ServiceResult.Success)
            {
                //Console.WriteLine("All email messages retrieved successfully.");
                //Console.WriteLine("\r\n");
            }
        }
        private static void OnNotificationEvent(object sender, NotificationEventArgs args)
        {
            // Extract the item ids for all NewMail Events in the list.
            var newMails = from e in args.Events.OfType <ItemEvent>()
                           where e.EventType == EventType.NewMail || e.EventType == EventType.Created || e.EventType == EventType.Modified || e.EventType == EventType.Deleted
                           select e.ItemId;

            var ids = newMails as ItemId[] ?? newMails.ToArray();

            if (!ids.Any())
            {
                return;
            }

            // Note: For the sake of simplicity, error handling is ommited here.
            // Just assume everything went fine
            var response = _ExchangeService.BindToItems(ids, new PropertySet(BasePropertySet.IdOnly, ItemSchema.DateTimeReceived, ItemSchema.Subject));
            var items    = response.Select(itemResponse => itemResponse.Item);

            foreach (var item in items)
            {
                if (item == null)
                {
                    continue;
                }
                //Console.Out.WriteLine("A new mail has been created. Received on {0}", item.DateTimeReceived);
                //Console.Out.WriteLine("Subject: {0}", item.Subject);
                Utils.ShowTaskbarNotifier(string.Format("Subject: {0}", item.Subject));
            }
        }
示例#5
0
        public IEnumerable <MailItem> GetMailFrom(WellKnownFolderName folderName, int maxItems)
        {
            var view = new ItemView(maxItems)
            {
                Traversal = ItemTraversal.Shallow,
            };

            FindItemsResults <Item> findResults = service.FindItems(folderName, view);

            if (findResults.Count() > 0)
            {
                var itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.ToRecipients, ItemSchema.Attachments)
                {
                    RequestedBodyType = BodyType.Text
                };
                ServiceResponseCollection <GetItemResponse> items =
                    service.BindToItems(findResults.Select(item => item.Id), itempropertyset);
                foreach (var item in items)
                {
                    var emailMessage = item.Item as EmailMessage;
                    var mailItem     = MailItem.FromExchangeMailMessage(emailMessage);

                    yield return(mailItem);
                }
            }
        }
        /// <summary>
        /// Get the MimeContent of each Item specified in itemIds and write it
        /// to a string.
        /// </summary>
        /// <param name="itemIds">ItemIds to retrieve</param>
        /// <param name="destinationFolderPath">Folder to save messages to</param>
        /// <param name="service">ExchangeService to use to make EWS calls</param>
        /// <param name="TheMime">MIME string to set</param>
        public static void DumpMIMEToString(
            List <ItemId> itemIds,
            ExchangeService service,
            ref string TheMime)
        {
            DebugLog.WriteVerbose(String.Format("Getting {0} items by ItemId.", itemIds.Count));
            string      MimeToReturn = string.Empty;
            PropertySet mimeSet      = new PropertySet(BasePropertySet.IdOnly);

            mimeSet.Add(EmailMessageSchema.MimeContent);
            mimeSet.Add(EmailMessageSchema.Subject);

            service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
            ServiceResponseCollection <GetItemResponse> responses = service.BindToItems(itemIds, mimeSet);

            DebugLog.WriteVerbose("Finished getting items.");

            foreach (GetItemResponse response in responses)
            {
                switch (response.Result)
                {
                case ServiceResult.Success:
                    if (response.Item.MimeContent == null)
                    {
                        throw new ApplicationException("No MIME content to write");
                    }
                    UTF8Encoding oUTF8Encoding = new UTF8Encoding();
                    MimeToReturn = oUTF8Encoding.GetString(response.Item.MimeContent.Content);

                    break;

                case ServiceResult.Error:
                    MimeToReturn =
                        "ErrorCode:           " + response.ErrorCode.ToString() + "\r\n" +
                        "\r\nErrorMessage:    " + response.ErrorMessage + "\r\n";

                    break;

                case ServiceResult.Warning:
                    throw new NotImplementedException("DumpMIMEToString doesn't handle ServiceResult.Warning.");

                default:
                    throw new NotImplementedException("DumpMIMEToString encountered an unexpected ServiceResult.");
                }
            }

            TheMime = MimeToReturn;

            DebugLog.WriteVerbose("Finished dumping MimeContents for each item.");
        }
示例#7
0
        /// <summary>
        /// GetEmailAttachment
        /// </summary>
        /// <returns>Result</returns>
        private byte[] GetEmailAttachment()
        {
            byte[] emailAttach = null;
            try
            {
                _log.Debug("GetEmailAttachment Start");

                var attachId = CommonHelper.DecodeUrl(Request.Form["AttachmentId"]);
                if (!AttachmentHelper.TryGetAttachmentResult(attachId, out emailAttach))
                {
                    var ewsUrl   = CommonHelper.DecodeUrl(Request.Form["EwsUrl"]);
                    var ewsId    = CommonHelper.DecodeUrl(Request.Form["EwsId"]);
                    var ewsToken = CommonHelper.DecodeUrl(Request.Form["EwsToken"]);
                    _log.Debug($"GetEmailAttachment EWSUrl: {ewsUrl}");

                    ExchangeService service = new ExchangeService();
                    service.Url         = new Uri(ewsUrl);
                    service.Credentials = new OAuthCredentials("Bearer " + ewsToken);
                    service.Timeout     = 360 * 1000;

                    List <ItemId> itemIds = new List <ItemId>()
                    {
                        ewsId
                    };
                    var items       = service.BindToItems(itemIds, new PropertySet());
                    var itemMessage = items.FirstOrDefault().Item;

                    itemMessage.Load(new PropertySet(ItemSchema.Attachments));
                    if (itemMessage.HasAttachments)
                    {
                        var attchs = itemMessage.Attachments;
                        foreach (FileAttachment attachment in attchs)
                        {
                            attachment.Load();
                            if (attachId == attachment.Id)
                            {
                                emailAttach = attachment.Content;
                            }
                            AttachmentHelper.SetAttachmentResult(attachment.Id, attachment.Content);
                        }
                    }
                }
                _log.Debug("GetEmailAttachment End");
            }
            catch (Exception ex)
            {
                _log.Debug($"GetEmailAttachment Exception: {ex.Message}");
            }
            return(emailAttach);
        }
        public Item GetItem(ItemId itemId)
        {
            List <ItemId> items = new List <ItemId>()
            {
                itemId
            };

            PropertySet properties = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Body, EmailMessageSchema.Sender, EmailMessageSchema.Subject);

            properties.RequestedBodyType = BodyType.Text;
            ServiceResponseCollection <GetItemResponse> response = _service.BindToItems(items, properties);

            return(response[0].Item);
        }
示例#9
0
        //itemId 转mailMessage
        public static List <EmailMessage> BatchGetEmailIlems(ExchangeService service, Collection <ItemId> itemid)
        {
            //绑定属性
            PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly,
                                                      EmailMessageSchema.InternetMessageId,      //Message Id
                                                      EmailMessageSchema.InternetMessageHeaders, //Message Hesder

                                                      EmailMessageSchema.HasAttachments,
                                                      EmailMessageSchema.Attachments,
                                                      EmailMessageSchema.ConversationIndex, //Thread-Inder
                                                      EmailMessageSchema.ConversationTopic, //Thread-Topic
                                                      EmailMessageSchema.From,              //From
                                                      EmailMessageSchema.ToRecipients,      //To
                                                      EmailMessageSchema.CcRecipients,      //Cc
                                                      EmailMessageSchema.ReplyTo,           //ReplayTo
                                                      EmailMessageSchema.InReplyTo,         //In-Replay-To
                                                      EmailMessageSchema.References,        //References
                                                      EmailMessageSchema.Subject,           //Subject
                                                      EmailMessageSchema.TextBody,
                                                      EmailMessageSchema.Attachments,
                                                      EmailMessageSchema.DateTimeSent,     //Sent Date
                                                      EmailMessageSchema.DateTimeReceived, //Received Date
                                                      EmailMessageSchema.Sender,
                                                      EmailMessageSchema.MimeContent,      //导出到eml文件
                                                      EmailMessageSchema.IsRead,
                                                      EmailMessageSchema.EffectiveRights,
                                                      EmailMessageSchema.ReceivedBy); //邮件已读状态

            ServiceResponseCollection <GetItemResponse> respone = service.BindToItems(itemid, propertySet);
            List <EmailMessage> messageItems = new List <EmailMessage>();

            foreach (GetItemResponse getItemRespone in respone)
            {
                try
                {
                    Item         item    = getItemRespone.Item;
                    EmailMessage message = (EmailMessage)item;

                    messageItems.Add(message);
                }
                catch (Exception ex)
                {
                    // Console.WriteLine("Exception with getting a message:{0}", ex.Message);
                    throw;
                }
            }
            return(messageItems);
        }
        /// <summary>
        /// Get the MimeContent of each Item specified in itemIds and write it
        /// to the destination folder.
        /// </summary>
        /// <param name="itemIds">ItemIds to retrieve</param>
        /// <param name="destinationFolderPath">Folder to save messages to</param>
        /// <param name="service">ExchangeService to use to make EWS calls</param>
        public static void DumpMIME(
            List <ItemId> itemIds,
            string destinationFolderPath,
            ExchangeService service)
        {
            DebugLog.WriteVerbose(String.Format("Getting {0} items by ItemId.", itemIds.Count));

            PropertySet mimeSet = new PropertySet(BasePropertySet.IdOnly);

            mimeSet.Add(EmailMessageSchema.MimeContent);
            mimeSet.Add(EmailMessageSchema.Subject);


            //mimeSet.Add(AppointmentSchema.MimeContent);
            //mimeSet.Add(AppointmentSchema.Subject);
            //mimeSet.Add(AppointmentSchema.RequiredAttendees);
            //mimeSet.Add(AppointmentSchema.OptionalAttendees);
            service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
            ServiceResponseCollection <GetItemResponse> responses = service.BindToItems(itemIds, mimeSet);

            DebugLog.WriteVerbose("Finished getting items.");

            foreach (GetItemResponse response in responses)
            {
                switch (response.Result)
                {
                case ServiceResult.Success:
                    DumpMIME(response.Item, destinationFolderPath);
                    break;

                case ServiceResult.Error:
                    DumpErrorResponseXML(response, destinationFolderPath);
                    break;

                case ServiceResult.Warning:
                    throw new NotImplementedException("DumpMIME doesn't handle ServiceResult.Warning.");

                default:
                    throw new NotImplementedException("DumpMIME encountered an unexpected ServiceResult.");
                }
            }

            DebugLog.WriteVerbose("Finished dumping MimeContents for each item.");
        }
        /// <summary>
        /// The get mail box content.
        /// </summary>
        /// <param name="folderName">
        /// The folder name.
        /// </param>
        /// <param name="mailbox">
        /// The mailbox.
        /// </param>
        /// <returns>
        /// The <see cref="List"/>.
        /// </returns>
        public static List <EmailParsingData> GetMailBoxContent(WellKnownFolderName folderName, string mailBox, string itemClass = "")
        {
            var mailBoxContent = new List <EmailParsingData>();

            var propertySet = new PropertySet(BasePropertySet.IdOnly, propertyDefinitionBases);
            var itemView    = new ItemView(1111);
            var service     = new ExchangeService(ExchangeVersion.Exchange2010_SP2)
            {
                UseDefaultCredentials = true
            };

            service.AutodiscoverUrl(mailBox);
            try
            {
                var findResult = itemClass == string.Empty ?
                                 service.FindItems(new FolderId(folderName, mailBox), itemView) :
                                 service.FindItems(new FolderId(folderName, mailBox), new SearchFilter.IsEqualTo(ItemSchema.ItemClass, itemClass), itemView); // "REPORT.IPM.Note.NDR" "REPORT.IPM.Note.DR"

                foreach (var item in findResult)
                {
                    var itemBody = service.BindToItems(new[] { item.Id }, propertySet).First().Item;
                    mailBoxContent.Add(new EmailParsingData
                    {
                        //itemId = item.Id,
                        ItemClass            = itemBody.ItemClass,
                        CreationTime         = itemBody.DateTimeCreated,
                        LastModificationTime = itemBody.LastModifiedTime,
                        Subject = itemBody.Subject,
                        //Body = itemBody.Body,
                        DisplayTo      = itemBody.DisplayTo,
                        DisplayCc      = itemBody.DisplayCc,
                        ConversationId = itemBody.ConversationId
                    });
                }

                return(mailBoxContent);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
示例#12
0
        public static Collection<EmailMessage> BatchGetEmailItems(ExchangeService service, Collection<ItemId> itemIds)
        {

            // Create a property set that limits the properties returned by the Bind method to only those that are required.
            PropertySet propSet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Subject, EmailMessageSchema.ToRecipients);

            // Get the items from the server.
            // This method call results in a GetItem call to EWS.
            ServiceResponseCollection<GetItemResponse> response = service.BindToItems(itemIds, propSet);

            // Instantiate a collection of EmailMessage objects to populate from the values that are returned by the Exchange server.
            Collection<EmailMessage> messageItems = new Collection<EmailMessage>();


            foreach (GetItemResponse getItemResponse in response)
            {
                try
                {
                    Item item = getItemResponse.Item;
                    EmailMessage message = (EmailMessage)item;
                    messageItems.Add(message);
                    // Print out confirmation and the last eight characters of the item ID.
                    System.Console.WriteLine("Found item {0}.", message.Id.ToString().Substring(144));
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("Exception while getting a message: {0}", ex.Message);
                }
            }

            // Check for success of the BindToItems method call.
            if (response.OverallResult == ServiceResult.Success)
            {
                System.Console.WriteLine("All email messages retrieved successfully.");
                System.Console.WriteLine("\r\n");
            }

            return messageItems;
        }
示例#13
0
        /// <summary>
        /// Get the MimeContent of each Item specified in itemIds and write it
        /// to the destination folder.
        /// </summary>
        /// <param name="itemIds">ItemIds to retrieve</param>
        /// <param name="destinationFolderPath">Folder to save messages to</param>
        /// <param name="service">ExchangeService to use to make EWS calls</param>
        public static void DumpMIME(
            List<ItemId> itemIds,
            string destinationFolderPath,
            ExchangeService service)
        {
            DebugLog.WriteVerbose(String.Format("Getting {0} items by ItemId.", itemIds.Count));

            PropertySet mimeSet = new PropertySet(BasePropertySet.IdOnly);

            mimeSet.Add(EmailMessageSchema.MimeContent);
            mimeSet.Add(EmailMessageSchema.Subject);

            //mimeSet.Add(AppointmentSchema.MimeContent);
            //mimeSet.Add(AppointmentSchema.Subject);
            //mimeSet.Add(AppointmentSchema.RequiredAttendees);
            //mimeSet.Add(AppointmentSchema.OptionalAttendees);
            ServiceResponseCollection<GetItemResponse> responses = service.BindToItems(itemIds, mimeSet);

            DebugLog.WriteVerbose("Finished getting items.");

            foreach (GetItemResponse response in responses)
            {
                switch (response.Result)
                {
                    case ServiceResult.Success:
                        DumpMIME(response.Item, destinationFolderPath);
                        break;
                    case ServiceResult.Error:
                        DumpErrorResponseXML(response, destinationFolderPath);
                        break;
                    case ServiceResult.Warning:
                        throw new NotImplementedException("DumpMIME doesn't handle ServiceResult.Warning.");
                    default:
                        throw new NotImplementedException("DumpMIME encountered an unexpected ServiceResult.");
                }
            }

            DebugLog.WriteVerbose("Finished dumping MimeContents for each item.");
        }
示例#14
0
        // LoadItem
        // This will load an item by ID.
        // Test code to load a folder object with many properties - modify as needed for your code.
        bool LoadItem(ExchangeService oService, ItemId oItemId, out Item oItem)
        {
            bool bRet = true;

            ExtendedPropertyDefinition Prop_IsHidden = new ExtendedPropertyDefinition(0x10f4, MapiPropertyType.Boolean);

            // PR_ARCHIVE_TAG  0x3018
            ExtendedPropertyDefinition Prop_PidTagPolicyTag = new ExtendedPropertyDefinition(0x66B1, MapiPropertyType.Long);

            // PR_POLICY_TAG 0x3019   Data type: PtypBinary, 0x0102
            ExtendedPropertyDefinition Prop_PR_POLICY_TAG = new ExtendedPropertyDefinition(0x3019, MapiPropertyType.Binary);

            // PR_RETENTION_FLAGS 0x301D (12317)  PtypInteger32
            ExtendedPropertyDefinition Prop_Retention_Flags = new ExtendedPropertyDefinition(0x301D, MapiPropertyType.Integer);

            // PR_RETENTION_PERIOD 0x301A (12314)  PtypInteger32, 0x0003
            ExtendedPropertyDefinition Prop_Retention_Period = new ExtendedPropertyDefinition(0x301A, MapiPropertyType.Integer);


            Item oReturnItem = null;

            oItem = null;

            List <ItemId> oItems = new List <ItemId>();

            oItems.Add(oItemId);

            PropertySet oPropertySet = new PropertySet(
                BasePropertySet.IdOnly,
                EmailMessageSchema.ItemClass,
                EmailMessageSchema.Subject);

            // Add more properties?
            oPropertySet.Add(Prop_IsHidden);
            oPropertySet.Add(EmailMessageSchema.DateTimeCreated);
            oPropertySet.Add(EmailMessageSchema.DateTimeReceived);
            oPropertySet.Add(EmailMessageSchema.DateTimeSent);
            //oPropertySet.Add(EmailMessageSchema.RetentionDate);
            oPropertySet.Add(EmailMessageSchema.ToRecipients);
            oPropertySet.Add(EmailMessageSchema.MimeContent);
            //oPropertySet.Add(EmailMessageSchema.StoreEntryId);
            oPropertySet.Add(EmailMessageSchema.Size);

            oPropertySet.Add(Prop_Retention_Period);
            oPropertySet.Add(Prop_PR_POLICY_TAG);
            oPropertySet.Add(Prop_Retention_Flags);

            int    iVal    = 0;
            long   lVal    = 0;
            object oVal    = null;
            bool   boolVal = false;

            ServiceResponseCollection <GetItemResponse> oGetItemResponses = oService.BindToItems(oItems, oPropertySet);

            StringBuilder oSB = new StringBuilder();

            foreach (GetItemResponse oGetItemResponse in oGetItemResponses)
            {
                switch (oGetItemResponse.Result)
                {
                case ServiceResult.Success:

                    oReturnItem = oGetItemResponse.Item;


                    oSB.AppendFormat("Subject: {0}\r\n", oReturnItem.Subject);
                    oSB.AppendFormat("Class: {0}\r\n", oReturnItem.ItemClass);
                    oSB.AppendFormat("DateTimeCreated: {0}\r\n", oReturnItem.DateTimeCreated.ToString());
                    oSB.AppendFormat("Size: {0}\r\n", oReturnItem.Size.ToString());


                    if (oReturnItem.TryGetProperty(Prop_IsHidden, out boolVal))
                    {
                        oSB.AppendFormat("PR_IS_HIDDEN: {0}\r\n", boolVal);
                    }
                    else
                    {
                        oSB.AppendLine("PR_IS_HIDDEN: Not found.");
                    }

                    if (oReturnItem.TryGetProperty(Prop_PR_POLICY_TAG, out oVal))
                    {
                        oSB.AppendFormat("PR_POLICY_TAG: {0}\r\n", oVal);
                    }
                    //else
                    //    oSB.AppendLine("PR_RETENTION_TAG: Not found.");

                    if (oReturnItem.TryGetProperty(Prop_Retention_Flags, out iVal))
                    {
                        oSB.AppendFormat("PR_RETENTION_FLAGS: {0}\r\n", iVal);
                    }
                    //else
                    //    oSB.AppendLine("PR_RETENTION_FLAGS: Not found.");

                    if (oReturnItem.TryGetProperty(Prop_Retention_Period, out iVal))
                    {
                        oSB.AppendFormat("PR_RETENTION_PERIOD:  {0}\r\n", iVal);
                    }
                    //else
                    //    oSB.AppendLine("PR_RETENTION_PERIOD: Not found.");

                    //// The following is for geting the MIME string
                    //if (oGetItemResponse.Item.MimeContent == null)
                    //{
                    //    // Do something
                    //}
                    //UTF8Encoding oUTF8Encoding = new UTF8Encoding();
                    //string sMIME = oUTF8Encoding.GetString(oGetItemResponse.Item.MimeContent.Content);

                    MessageBox.Show(oSB.ToString(), "ServiceResult.Success");

                    break;

                case ServiceResult.Error:
                    string sError =
                        "ErrorCode:           " + oGetItemResponse.ErrorCode.ToString() + "\r\n" +
                        "\r\nErrorMessage:    " + oGetItemResponse.ErrorMessage + "\r\n";

                    MessageBox.Show(sError, "ServiceResult.Error");

                    break;

                case ServiceResult.Warning:
                    string sWarning =
                        "ErrorCode:           " + oGetItemResponse.ErrorCode.ToString() + "\r\n" +
                        "\r\nErrorMessage:    " + oGetItemResponse.ErrorMessage + "\r\n";

                    MessageBox.Show(sWarning, "ServiceResult.Warning");

                    break;
                    //default:
                    //    // Should never get here.
                    //    string sSomeError =
                    //            "ErrorCode:           " + oGetItemResponse.ErrorCode.ToString() + "\r\n" +
                    //            "\r\nErrorMessage:    " + oGetItemResponse.ErrorMessage + "\r\n";

                    //    MessageBox.Show(sSomeError, "Some sort of error");
                    //    break;
                }
            }

            oItem = oReturnItem;

            return(bRet);
        }
示例#15
0
        //private string DeNullString(string s)
        //{
        //    if (s == null)
        //        return "";
        //    else
        //        return s;
        //}


        // LoadItem
        // This will load an item by ID.
        // Test code to load a folder object with many properties - modify as needed for your code.
        bool LoadItem(ExchangeService oService, ItemId oItemId, out Item oItem)
        {
            bool bRet = true;

            ExtendedPropertyDefinition Prop_IsHidden = new ExtendedPropertyDefinition(0x10f4, MapiPropertyType.Boolean);

            Item oReturnItem = null;

            oItem = null;

            List <ItemId> oItems = new List <ItemId>();

            oItems.Add(oItemId);

            PropertySet oPropertySet = new PropertySet(
                BasePropertySet.IdOnly,
                EmailMessageSchema.ItemClass,
                EmailMessageSchema.Subject);

            // Add more properties?
            oPropertySet.Add(Prop_IsHidden);
            oPropertySet.Add(EmailMessageSchema.DateTimeCreated);
            oPropertySet.Add(EmailMessageSchema.DateTimeReceived);
            oPropertySet.Add(EmailMessageSchema.DateTimeSent);
            //oPropertySet.Add(EmailMessageSchema.RetentionDate);
            oPropertySet.Add(EmailMessageSchema.ToRecipients);
            oPropertySet.Add(EmailMessageSchema.MimeContent);
            oPropertySet.Add(EmailMessageSchema.StoreEntryId);
            oPropertySet.Add(EmailMessageSchema.Size);

            oService.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
            ServiceResponseCollection <GetItemResponse> oGetItemResponses = oService.BindToItems(oItems, oPropertySet);


            foreach (GetItemResponse oGetItemResponse in oGetItemResponses)
            {
                switch (oGetItemResponse.Result)
                {
                case ServiceResult.Success:

                    oReturnItem = oGetItemResponse.Item;

                    // EmailMessage oEmailMessage = (EmailMessage)oReturnItem; // recasting example

                    MessageBox.Show("ServiceResult.Success");

                    //// The following is for geting the MIME string
                    //if (oGetItemResponse.Item.MimeContent == null)
                    //{
                    //    // Do something
                    //}
                    //UTF8Encoding oUTF8Encoding = new UTF8Encoding();
                    //string sMIME = oUTF8Encoding.GetString(oGetItemResponse.Item.MimeContent.Content);

                    break;

                case ServiceResult.Error:
                    string sError =
                        "ErrorCode:           " + oGetItemResponse.ErrorCode.ToString() + "\r\n" +
                        "\r\nErrorMessage:    " + oGetItemResponse.ErrorMessage + "\r\n";

                    MessageBox.Show(sError, "ServiceResult.Error");

                    break;

                case ServiceResult.Warning:
                    string sWarning =
                        "ErrorCode:           " + oGetItemResponse.ErrorCode.ToString() + "\r\n" +
                        "\r\nErrorMessage:    " + oGetItemResponse.ErrorMessage + "\r\n";

                    MessageBox.Show(sWarning, "ServiceResult.Warning");

                    break;
                    //default:
                    //    // Should never get here.
                    //    string sSomeError =
                    //            "ErrorCode:           " + oGetItemResponse.ErrorCode.ToString() + "\r\n" +
                    //            "\r\nErrorMessage:    " + oGetItemResponse.ErrorMessage + "\r\n";

                    //    MessageBox.Show(sSomeError, "Some sort of error");
                    //    break;
                }
            }

            oItem = oReturnItem;

            return(bRet);
        }
示例#16
0
        public JsonResult SaveEmailToServer(SaveEmailModel model)
        {
            try
            {
                _log.Debug("SaveEmailToServer Start");
                var fileName = CommonHelper.DecodeUrl(model.FileName);
                var tokenId  = CommonHelper.GetToken(model.TokenId);
                var docId    = CommonHelper.DecodeUrl(model.Docid);
                var ewsUrl   = CommonHelper.DecodeUrl(model.EwsUrl);
                var ewsId    = CommonHelper.DecodeUrl(model.EwsId);
                var ewsToken = CommonHelper.DecodeUrl(model.EwsToken);
                _log.Debug($"SaveEmailToServer: {fileName}");

                _log.Debug($"SaveEmailToServer ExchangeService Start,  EWSUrl: {ewsUrl}");
                ExchangeService service = new ExchangeService();
                service.Url         = new Uri(ewsUrl);
                service.Credentials = new OAuthCredentials("Bearer " + ewsToken);
                service.Timeout     = 360 * 1000;

                List <ItemId> itemIds = new List <ItemId>()
                {
                    ewsId
                };
                var items       = service.BindToItems(itemIds, new PropertySet());
                var itemMessage = items.FirstOrDefault().Item;

                itemMessage.Load(new PropertySet(ItemSchema.MimeContent));
                MimeContent mimconm = itemMessage.MimeContent;
                _log.Debug($"SaveEmailToServer ExchangeService End");

                _log.Debug($"SaveEmailToServer UploadFile Start");
                SaveFileModel uploadModel = new SaveFileModel()
                {
                    Base64Str = mimconm.Content,
                    FileName  = fileName,
                    Docid     = docId,
                    TokenId   = tokenId,
                    Ondup     = model.Ondup
                };

                IAS7APIHelper helper        = new AS7APIHelper();
                var           uploadFileRes = helper.UploadFile(uploadModel);
                _log.Debug($"SaveEmailToServer UploadFile End");

                if (uploadFileRes.ErrorCode == 403002039)
                {
                    uploadFileRes.FileName = helper.GetSuggestFileName(tokenId, docId, fileName);
                }
                _log.Debug("SaveEmailToServer End");
                return(Json(new JsonModel {
                    Success = true, StatusCode = uploadFileRes.ErrorCode, Data = JsonConvert.SerializeObject(uploadFileRes)
                }));
            }
            catch (Exception ex)
            {
                _log.Debug($"SaveEmailToServer Exception: {ex.Message}");
                return(Json(new JsonModel {
                    Success = false, Message = ex.Message
                }));
            }
        }
示例#17
0
        /// <summary>
        /// Check on mail folder last received asuntos
        /// </summary>
        /// <param name="prmLastDateTimeChecked">Last date registered of check to filter folder</param>
        /// <returns></returns>
        public List <Entidades.Asunto> GetLastAsuntosAdded(DateTime prmLastDateTimeChecked)
        {
            // Generate a new asunto list to return
            List <Entidades.Asunto> lstAsuntoToProcess = new List <Entidades.Asunto>();
            // Get filtering properties for search on inbox
            SearchFilter filterCriteria = getFilterForAsuntosSearch(prmLastDateTimeChecked.AddSeconds(10));
            // Get view with specify properties for search
            ItemView viewContainer = getResultViewForAsuntoList();
            // Generate a collection for matching items
            FindItemsResults <Item> resultOfSearch = mailServiceConnection.FindItems(asuntoFolder, filterCriteria, viewContainer);

            if (resultOfSearch.TotalCount > 0)
            {
                // Generate a new ServiceResponseCollection with items saved
                ServiceResponseCollection <GetItemResponse> itemWithBodyAndDateReceived = mailServiceConnection.BindToItems(resultOfSearch.Select(item => item.Id), new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.DateTimeReceived));
                // Iterates over all results finded
                foreach (var item in itemWithBodyAndDateReceived.Select(item => item.Item).ToArray())
                {
                    // Save temporaly in a variable subject result
                    string subjectWithAsunto = item.Subject;
                    // Get Start point for cutting string resullt
                    int intStartCutString = subjectWithAsunto.IndexOf(startSubstringCut) + startSubstringCut.Length;
                    int intEndCutString   = subjectWithAsunto.LastIndexOf(endSubstringCut);
                    // With end and start can obtain asunto number
                    string asuntoNumber     = subjectWithAsunto.Substring(intStartCutString, (intEndCutString - intStartCutString));
                    string shortDescription = getShortDescriptionByFiltering(item.Body);
                    // Generate a new entidades of asunto and add to list
                    lstAsuntoToProcess.Add(new Entidades.Asunto()
                    {
                        Numero = asuntoNumber, DescripcionBreve = shortDescription, LoadedOnSolucionameDate = item.DateTimeReceived
                    });
                }
            }
            // Return processed list
            return(lstAsuntoToProcess);
        }
示例#18
0
        /// <summary>
        /// Get the MimeContent of each Item specified in itemIds and write it
        /// to a string.
        /// </summary>
        /// <param name="itemIds">ItemIds to retrieve</param>
        /// <param name="destinationFolderPath">Folder to save messages to</param>
        /// <param name="service">ExchangeService to use to make EWS calls</param>
        /// <param name="TheMime">MIME string to set</param>
        public static void DumpMIMEToString(
            List<ItemId> itemIds,
            ExchangeService service,
            ref string TheMime)
        {
            DebugLog.WriteVerbose(String.Format("Getting {0} items by ItemId.", itemIds.Count));
            string MimeToReturn = string.Empty;
            PropertySet mimeSet = new PropertySet(BasePropertySet.IdOnly);

            mimeSet.Add(EmailMessageSchema.MimeContent);
            mimeSet.Add(EmailMessageSchema.Subject);

            ServiceResponseCollection<GetItemResponse> responses = service.BindToItems(itemIds, mimeSet);

            DebugLog.WriteVerbose("Finished getting items.");

            foreach (GetItemResponse response in responses)
            {
                switch (response.Result)
                {
                    case ServiceResult.Success:
                        if (response.Item.MimeContent == null)
                        {
                            throw new ApplicationException("No MIME content to write");
                        }
                        UTF8Encoding oUTF8Encoding = new UTF8Encoding();
                        MimeToReturn = oUTF8Encoding.GetString(response.Item.MimeContent.Content);

                        break;
                    case ServiceResult.Error:
                        MimeToReturn =
                                "ErrorCode:           " + response.ErrorCode.ToString() + "\r\n" +
                                "\r\nErrorMessage:    " + response.ErrorMessage + "\r\n";

                        break;
                    case ServiceResult.Warning:
                        throw new NotImplementedException("DumpMIMEToString doesn't handle ServiceResult.Warning.");
                    default:
                        throw new NotImplementedException("DumpMIMEToString encountered an unexpected ServiceResult.");
                }
            }

            TheMime = MimeToReturn;

            DebugLog.WriteVerbose("Finished dumping MimeContents for each item.");
        }
示例#19
0
        /// <summary>
        /// Dump the properties from the given PropertySet of every item in the 
        /// ItemId list to XML files.
        /// </summary>
        /// <param name="itemIds">List of ItemIds to get</param>
        /// <param name="propertySet">PropertySet to use when getting items</param>
        /// <param name="destinationFolderPath">Folder to save messages to</param>
        /// <param name="service">ExchangeService to use to make EWS calls</param>
        public static void DumpXML(
            List<ItemId> itemIds,
            PropertySet propertySet,
            string destinationFolderPath,
            ExchangeService service)
        {
            DebugLog.WriteVerbose(String.Format("Getting {0} items by ItemId.", itemIds.Count));
            ServiceResponseCollection<GetItemResponse> responses = service.BindToItems(itemIds, propertySet);
            DebugLog.WriteVerbose("Finished getting items.");

            DebugLog.WriteVerbose("Started writing XML dumps to files.");
            foreach (GetItemResponse response in responses)
            {
                switch (response.Result)
                {
                    case ServiceResult.Success:
                        DumpXML(response.Item, destinationFolderPath);
                        break;
                    case ServiceResult.Error:
                        DumpErrorResponseXML(response, destinationFolderPath);
                        break;
                    case ServiceResult.Warning:
                        throw new NotImplementedException("DumpXML doesn't handle ServiceResult.Warning.");
                    default:
                        throw new NotImplementedException("Unexpected ServiceResult.");
                }
            }

            DebugLog.WriteVerbose("Finished writing XML dumps to files.");
        }
示例#20
0
        /// <summary>
        /// Gets the emails.
        /// </summary>
        /// <param name="emailCatalog">
        /// The email Catalog.
        /// </param>
        /// <returns>
        /// </returns>
        public string GetEmails(EmailCatalog emailCatalog)
        {
            var sb      = new StringBuilder();
            var service = new ExchangeService(ExchangeVersion.Exchange2010);
            var client  = this.FormsAuthenticationHelper.CurrentClient;

            if (client != null)
            {
                service.Credentials = new WebCredentials(
                    client.Email.Split('@')[0],
                    MyCryptoHelper.DecryptStringAES(
                        client.Password,
                        ConfigurationManager.AppSettings["KeyForAESCrypto"]));
                service.AutodiscoverUrl(client.Email);

                try
                {
                    FindItemsResults <Item> emails;
                    switch (emailCatalog)
                    {
                    case EmailCatalog.Inbox:

                        emails = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));
                        break;

                    case EmailCatalog.SentItems:
                        emails = service.FindItems(WellKnownFolderName.SentItems, new ItemView(int.MaxValue));
                        break;

                    case EmailCatalog.DeletedItems:
                        emails = service.FindItems(WellKnownFolderName.DeletedItems, new ItemView(int.MaxValue));
                        break;

                    case EmailCatalog.Drafts:
                        emails = service.FindItems(WellKnownFolderName.Drafts, new ItemView(int.MaxValue));
                        break;

                    default:
                        emails = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));
                        break;
                    }

                    var clientId  = this.FormsAuthenticationHelper.CurrentClient.Id;
                    var catalogId =
                        this.RepositoryCatalogs.SearchFor(x => x.CatalogName == emailCatalog.ToString())
                        .Select(x => x.CatalogId)
                        .SingleOrDefault();

                    var items = service.BindToItems(
                        emails.Select(item => item.Id),
                        new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Subject, ItemSchema.Body));
                    var emailItemCollection =
                        items.Select(
                            item =>
                            new EmailItem
                    {
                        Body              = !string.IsNullOrEmpty(item.Item.Body.ToString()) ? item.Item.Body.ToString() : "!!!Email without body!!!",
                        CreationDate      = item.Item.DateTimeCreated,
                        InternetMessageId =
                            item.Item is EmailMessage && !string.IsNullOrEmpty(((EmailMessage)item.Item).InternetMessageId)
                                        ? ((EmailMessage)item.Item).InternetMessageId
                                        : "InvalidInternetMessageId",
                        Subject   = item.Item.Subject ?? "!!!Email without subject!!!",
                        CatalogId = catalogId,
                        ClientId  = clientId
                    }).ToList();

                    var existsEmails =
                        this.RepositoryEmailItems.SearchFor(x => x.CatalogId == catalogId && x.ClientId == clientId);
                    foreach (var emailItem in emailItemCollection)
                    {
                        // add to db if not exist
                        EmailItem item = emailItem;
                        if (
                            !existsEmails.Any(e => e.InternetMessageId == item.InternetMessageId))
                        {
                            this.RepositoryEmailItems.Add(emailItem);
                            this.RepositoryEmailItems.Save();
                        }
                    }

                    // var allEmailsInCatalog = this.RepositoryClients.GetById(clientId).EmailItems
                    // .Where(emailItem => emailItem.CatalogId == catalogId)
                    // .OrderByDescending(element => element.CreationDate);
                    var allEmailsInCatalog =
                        this.RepositoryEmailItems.GetAll().Where(element => element.CatalogId == catalogId &&
                                                                 element.ClientId == clientId).OrderByDescending(element => element.CreationDate);

                    foreach (var item in allEmailsInCatalog)
                    {
                        var subjectWithId = new SubjectWithId
                        {
                            Subject      = item.Subject,
                            Id           = item.InternetMessageId,
                            DateCreation =
                                item.CreationDate.ToString(
                                    CultureInfo.InvariantCulture)
                        };
                        var jsonUser = JsonConvert.SerializeObject(subjectWithId);
                        sb.Append(jsonUser + ",");
                    }

                    sb.Remove(sb.Length - 1, 1);
                }
                catch (Exception ex)
                {
                    return(ex.Message);
                }
            }

            return(string.Format(Constants.FormatJson, sb));
        }
        private static IEnumerable<Attendee> GetAtendees(ExchangeService service, ServiceId serviceId)
        {
            var result = service.BindToItems(new[] {new ItemId(serviceId.UniqueId)},
                                             new PropertySet(BasePropertySet.FirstClassProperties)).SingleOrDefault();

            var appointment = (Appointment) result.Item;

            // TODO re factor attendee creation to remove code duplication
            return appointment.RequiredAttendees.Select(a => new Attendee {
                Name = a.Name,
                ResponseType = a.ResponseType.ToString()
            });
        }
示例#22
0
        //private void Get

        private void ExtrairEmail()
        {
            ExchangeService service;

            #region TOBEIMPLEMENTEDAFTER
            //List<FileStream> fileStreams = new List<FileStream>();
            #endregion
            try
            {
                Console.WriteLine("Registering Exchange connection");

                service = new ExchangeService
                {
                    Credentials = new WebCredentials("*****@*****.**", "Ber@2020C@")
                };
            }
            catch
            {
                Console.WriteLine("new ExchangeService failed. Press enter to exit:");
                throw;
            }

            service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

            try
            {
                ItemView view = new ItemView(400, 0, OffsetBasePoint.Beginning);
                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);

                FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, view);
                ServiceResponseCollection <GetItemResponse> items = service.BindToItems(findResults.Select(item => item.Id), new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Subject, EmailMessageSchema.From, EmailMessageSchema.ToRecipients, EmailMessageSchema.CcRecipients, EmailMessageSchema.DateTimeReceived, EmailMessageSchema.Body, ItemSchema.Attachments, EmailMessageSchema.IsRead));
                var sortedItems = items.OrderBy(x => x.Item.DateTimeReceived);
                foreach (var item in sortedItems)
                {
                    EmailMessage message = EmailMessage.Bind(service, new ItemId(item.Item.Id.ToString()), new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));

                    MailItem mailItem = new MailItem();
                    mailItem.From            = ((Microsoft.Exchange.WebServices.Data.EmailAddress)item.Item[EmailMessageSchema.From]).Address;
                    mailItem.ToRecipients    = ((Microsoft.Exchange.WebServices.Data.EmailAddressCollection)item.Item[EmailMessageSchema.ToRecipients]).Select(recipient => recipient.Address).ToArray();
                    mailItem.CcRecipients    = ((Microsoft.Exchange.WebServices.Data.EmailAddressCollection)item.Item[EmailMessageSchema.CcRecipients]).Select(ccRecipients => ccRecipients.Address).ToArray();
                    mailItem.Subject         = item.Item.Subject;
                    mailItem.DataRecebimento = item.Item.DateTimeReceived;
                    mailItem.Body            = ConvertToPlainText(item.Item.Body.Text.ToString());
                    mailItem.isRead          = Convert.ToBoolean(item.Item[EmailMessageSchema.IsRead].ToString());

                    if (mailItem.Subject.Contains("Controle de ponto") /* &&  !mailItem.isRead*/)
                    {
                        foreach (Microsoft.Exchange.WebServices.Data.Attachment attachment in message.Attachments)
                        {
                            if (attachment is FileAttachment)
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                fileAttachment.Load();

                                if (!string.IsNullOrEmpty(_caminhoDestino))
                                {
                                    if (fileAttachment.Name.ToUpper().Contains(".XLSM"))
                                    {
                                        string dest     = Path.Combine(_caminhoDestino, fileAttachment.Name);
                                        string fileName = fileAttachment.Name;
                                        int    i        = 1;

                                        while (File.Exists(dest))
                                        {
                                            string previousIterator = "(" + (i - 1) + ")";
                                            fileName = fileName.Replace(".xlsm", "").Replace(previousIterator, "") + "(" + i + ").xlsm";
                                            dest     = Path.Combine(_caminhoDestino, fileName);
                                            i++;
                                        }

                                        dest = Path.Combine(_caminhoDestino, fileName);
                                        fileAttachment.Load(dest);
                                        FileStream fileStream = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                                        fileAttachment.Load(fileStream);
                                        fileStream.Close();
                                        fileStream.Dispose();
                                        #region TOBEIMPLEMENTEDAFTER
                                        //fileStreams.Add(fileStream);
                                        #endregion
                                    }
                                }
                                else
                                {
                                    throw new ClassNotInitializedCorrectly("Para extrair o email você precisa initializar este objeto com o caminho de destino dos arquivos");
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Email lido");
                    }
                }
            }
            catch (System.Exception)
            {
                throw;
            }
            #region TOBEIMPLEMENTEDAFTER
            //return fileStreams;
            #endregion
        }