Exemple #1
0
        private void btnCopyToFolder_Click(object sender, EventArgs e)
        {
            initialMailListView();
            if (this.treeViewFolder.SelectedNode == null)
            {
                MessageBox.Show("Select a folder under Inbox firstly.");
                return;
            }

            if (this.listViewMail.Visible && this.listViewMail.SelectedItems.Count > 0)
            {
                ItemId       itemId = new ItemId(this.listViewMail.SelectedItems[0].SubItems[4].Text);
                EmailMessage em     = EmailMessage.Bind(service, itemId);

                if (this.treeViewFolder.SelectedNode.Name == em.ParentFolderId.UniqueId)
                {
                    MessageBox.Show("This folder is the same folder of mail, select another folder.");
                    return;
                }
                else
                {
                    em.Copy(new FolderId(this.treeViewFolder.SelectedNode.Name));
                    this.txtLog.Text += "Copy mail into folder success\r\nEWS API: Copy\r\nLocation:..\\EWS\\EWS\\Form1.cs(415)\r\n\r\n";
                    getMails(this.treeViewFolder.SelectedNode.Name, null);
                }
            }
            else
            {
                MessageBox.Show("Select a mail firstly");
                initialMailListView();
                return;
            }
        }
Exemple #2
0
        private void btnViewMail_Click(object sender, EventArgs e)
        {
            if (this.listViewMail.Visible && this.listViewMail.SelectedItems.Count > 0)
            {
                initialViewMailView();
                ItemId       itemId = new ItemId(this.listViewMail.SelectedItems[0].SubItems[4].Text);
                EmailMessage em     = EmailMessage.Bind(service, itemId);
                this.txtLog.Text = "View mail success\r\nEWS API: EmailMessage.Bind\r\nLocation:..\\EWS\\EWS\\Form1.cs(299)\r\n\r\n";

                this.txtFrom.Text                = em.From.Address;
                this.txtTo.Text                  = GetToString(em.ToRecipients);
                this.txtSubject.Text             = em.Subject;
                this.webBrowserBody.DocumentText = em.Body;

                if (em.HasAttachments)
                {
                    this.lblAttachedFile.Text = "Attached: ";
                    foreach (var item in em.Attachments)
                    {
                        this.lblAttachedFile.Text += item.Name;
                    }
                }

                em.IsRead = true;
                em.Update(ConflictResolutionMode.AutoResolve);
                this.txtLog.Text += "Mark as read success\r\nEWS API: Update\r\nLocation:..\\EWS\\EWS\\Form1.cs(316)\r\n\r\n";
            }
            else
            {
                MessageBox.Show("Select a mail firstly");
                initialMailListView();
                return;
            }
        }
Exemple #3
0
        static void SetPullNotifications(ExchangeService service)
        {
            // Initiate the subscription object, specifying the folder and events.
            PullSubscription subscription = service.SubscribeToPullNotifications(
                new FolderId[] { WellKnownFolderName.Inbox }, 5, null,
                EventType.NewMail, EventType.Created, EventType.Deleted);

            // Initiate the GetEvents method for the new subscription.
            GetEventsResults events = subscription.GetEvents();

            // Handle the results of the GetEvents method.
            foreach (ItemEvent itemEvent in events.ItemEvents)
            {
                switch (itemEvent.EventType)
                {
                case EventType.NewMail:
                    EmailMessage message = EmailMessage.Bind(service, itemEvent.ItemId);
                    break;

                case EventType.Created:
                    Item item = Item.Bind(service, itemEvent.ItemId);
                    break;

                case EventType.Deleted:
                    Console.WriteLine("Item deleted: " + itemEvent.ItemId.UniqueId);
                    break;
                }
            }
        }
Exemple #4
0
        private void Notify(object o)
        {
            User user = (User)o;

            Console.WriteLine("Notify for " + user.Id + "...");
            GetEventsResults results = user.Subscription.GetEvents();

            Console.WriteLine("Current Watermark: " + user.Subscription.Watermark);

            foreach (ItemEvent eventItem in results.ItemEvents)
            {
                string eventType = String.Empty;
                if (eventItem.EventType == EventType.NewMail)
                {
                    eventType = "新規";
                }
                else if (eventItem.EventType == EventType.Deleted)
                {
                    eventType = "削除";
                }
                else if (eventItem.EventType == EventType.Moved)
                {
                    eventType = "移動";
                }
                Console.WriteLine("ItemId: " + eventItem.ItemId);
                try {
                    EmailMessage message = EmailMessage.Bind(user.Service, eventItem.ItemId);
                    Console.WriteLine(eventType + " : " + message.Subject);
                    Console.WriteLine("Saved Watermark: " + user.Subscription.Watermark);
                } catch (Exception exception) {
                    Console.WriteLine(exception.Message);
                } finally {
                }
            }
        }
Exemple #5
0
    public static void Main(string[] args)
    {
        try {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
            service.Credentials = new WebCredentials("login", "pwd");
            service.AutodiscoverUrl("*****@*****.**");
            ItemView view = new ItemView(10);
            FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));

            if (findResults != null && findResults.Items != null && findResults.Items.Count > 0)
            {
                foreach (Item item in findResults.Items)
                {
                    EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
                    foreach (Attachment attachment in message.Attachments)
                    {
                        if (attachment is FileAttachment)
                        {
                            FileAttachment fileAttachment = attachment as FileAttachment;
                            fileAttachment.Load();
                            Console.WriteLine("Attachment name: " + fileAttachment.Name);
                        }
                    }
                    Console.WriteLine(item.Subject);
                }
            }
            else
            {
                Console.WriteLine("no items");
            }
        } catch (Exception e) {
            Console.WriteLine(e.Message);
        }
        Console.ReadLine();
    }
Exemple #6
0
        /// <summary>
        /// 获取邮件列表
        /// </summary>
        /// <param name="isRead">已读true/未读false</param>
        /// <param name="count">数量</param>
        /// <param name="config"></param>
        /// <returns>邮件列表</returns>
        public static List <EmailMessage> GetEmailList(bool isRead, int count, ExchangeAdminConfig config)
        {
            InitializeEws(config);
            List <EmailMessage> emails = new List <EmailMessage>();
            //创建过滤器
            SearchFilter            sf          = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, isRead);
            FindItemsResults <Item> findResults = null;

            try
            {
                findResults = Service.FindItems(WellKnownFolderName.Inbox, sf, new ItemView(count));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (findResults != null)
            {
                foreach (Item item in findResults.Items)
                {
                    EmailMessage email = EmailMessage.Bind(Service, item.Id);
                    emails.Add(email);
                }
            }

            return(emails);
        }
Exemple #7
0
        /// <summary>
        /// Gets text body of the specific email from MS Exchange Server by Email Subject
        /// </summary>
        /// <param name="microsoftUsername"></param>
        /// <param name="microsoftPassword"></param>
        /// <param name="microsoftDomainName"></param>
        /// <param name="emailAddress"></param>
        /// <param name="emailSubject"></param>
        public string GetTextEmailBodyByEmailSubjectFromExchangeServer(string microsoftUsername, string microsoftPassword, string microsoftDomainName, string emailAddress, string emailFolderName, string emailSubject)
        {
            var             textEmailBody   = string.Empty;
            ExchangeService exchangeService = null;

            try
            {
                exchangeService             = new ExchangeService();
                exchangeService.Credentials = new NetworkCredential(microsoftUsername, microsoftPassword, microsoftDomainName);
                exchangeService.AutodiscoverUrl(emailAddress);

                var folderView = new FolderView(1);
                var itemView   = new ItemView(1);
                itemView.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
                itemView.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);

                var folders     = exchangeService.FindFolders(emailFolderName.ToLower().Equals("inbox") ? WellKnownFolderName.MsgFolderRoot : WellKnownFolderName.Inbox, new SearchFilter.SearchFilterCollection(LogicalOperator.Or, new SearchFilter.IsEqualTo(FolderSchema.DisplayName, emailFolderName)), folderView);
                var folderId    = folders.FirstOrDefault().Id;
                var findResults = exchangeService.FindItems(folderId, new SearchFilter.SearchFilterCollection(LogicalOperator.Or, new SearchFilter.ContainsSubstring(ItemSchema.Subject, emailSubject)), itemView);

                foreach (Item item in findResults.Items)
                {
                    var propSet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Body, ItemSchema.TextBody);
                    var message = EmailMessage.Bind(exchangeService, item.Id, propSet);
                    textEmailBody = message.TextBody.Text;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(textEmailBody);
        }
Exemple #8
0
        private void processResult(PropertySet propSet, Item result)
        {
            switch (result.GetType().ToString())
            {
            case "Microsoft.Exchange.WebServices.Data.EmailMessage":
                EmailMessage message = EmailMessage.Bind(mailboxConnection, result.Id, propSet);

                if (!doNotMarkRead)
                {
                    message.IsRead = true;
                    message.Update(ConflictResolutionMode.AutoResolve);
                }

                WriteObject(message);
                break;

            case "Microsoft.Exchange.WebServices.Data.Appointment":
                Appointment appointment = Appointment.Bind(mailboxConnection, result.Id, propSet);

                WriteObject(appointment);
                break;

            default:
                WriteObject(result);
                break;
            }
        }
Exemple #9
0
        private EmailMessage[] GetMessageInfos(bool pushNotification, string contentListPath)
        {
            var contentList  = Node.LoadNode(contentListPath);
            var mailboxEmail = contentList["ListEmail"] as string;

            if (!pushNotification)
            {
                var service = ExchangeHelper.CreateConnection(mailboxEmail);
                if (service == null)
                {
                    return(new EmailMessage[0]);
                }

                var items = ExchangeHelper.GetItems(service, mailboxEmail);
                var infos = items.Select(item => EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Body, ItemSchema.Attachments, ItemSchema.MimeContent)));

                return(infos.ToArray());
            }
            else
            {
                var incomingEmails = SenseNet.Search.ContentQuery.Query(ContentRepository.SafeQueries.InFolder,
                                                                        new Search.QuerySettings {
                    EnableAutofilters = FilterStatus.Disabled
                },
                                                                        RepositoryPath.Combine(contentListPath, ExchangeHelper.PUSHNOTIFICATIONMAILCONTAINER));

                if (incomingEmails.Count == 0)
                {
                    return(new EmailMessage[0]);
                }

                var service = ExchangeHelper.CreateConnection(mailboxEmail);
                if (service == null)
                {
                    return(new EmailMessage[0]);
                }

                var msgs = new List <EmailMessage>();
                foreach (var emailnode in incomingEmails.Nodes)
                {
                    var ids = emailnode["Description"] as string;
                    if (string.IsNullOrEmpty(ids))
                    {
                        continue;
                    }

                    var idList = ids.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var id in idList)
                    {
                        var msg = EmailMessage.Bind(service, id, new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Body, ItemSchema.Attachments, ItemSchema.MimeContent));
                        msgs.Add(msg);
                    }

                    // delete email node
                    emailnode.ForceDelete();
                }
                return(msgs.ToArray());
            }
        }
Exemple #10
0
        private void Connection_OnNotificationEvent(object sender, NotificationEventArgs args)
        {
            lock (exService)
            {
                foreach (NotificationEvent e in args.Events)
                {
                    try
                    {
                        var          itemEvent = (ItemEvent)e;
                        EmailMessage message   = EmailMessage.Bind(args.Subscription.Service, itemEvent.ItemId);

                        switch (e.EventType)
                        {
                        case EventType.NewMail:
                            if (message.From.Address == ApplicationSettings.EmailRecipients.FDLSystem || message.DisplayTo == ApplicationSettings.EmailRecipients.FDL_CHK_Display)
                            {
                                NotifyNewMessage(message);
                            }
                            break;

                        default:
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex, "Connection_OnNotificationEvent()");
                    }
                }
            }
        }
Exemple #11
0
        private IEnumerable <Email> getMail(FindItemsResults <Item> findResults, ExchangeService service)
        {
            PropertySet propSet = new PropertySet(BasePropertySet.FirstClassProperties);

            if (bodyFormat.Equals("HTML Format"))
            {
                propSet.RequestedBodyType = BodyType.HTML;
            }
            else
            {
                propSet.RequestedBodyType = BodyType.Text;
            }

            foreach (Item result in findResults)
            {
                if (result.GetType().ToString().Equals("Microsoft.Exchange.WebServices.Data.EmailMessage"))
                {
                    EmailMessage message = EmailMessage.Bind(service, result.Id, propSet);
                    Email        retMail = new Email(message);

                    message.IsRead = true;
                    message.Update(ConflictResolutionMode.AutoResolve);

                    yield return(retMail);
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// Bind To EmailMessage by Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns>The Email Message</returns>
        public EmailMessage BindToEmailMessage(ItemId id)
        {
            if (id == null)
            {
                return(null);
            }

            PropertySet propSet = new PropertySet(
                BasePropertySet.IdOnly,
                ItemSchema.TextBody,
                EmailMessageSchema.Body,
                ItemSchema.Subject,
                EmailMessageSchema.From,
                EmailMessageSchema.Attachments,
                EmailMessageSchema.HasAttachments,
                EmailMessageSchema.DateTimeCreated,
                EmailMessageSchema.CcRecipients,
                EmailMessageSchema.BccRecipients,
                EmailMessageSchema.DisplayCc,
                EmailMessageSchema.DisplayTo,
                EmailMessageSchema.ToRecipients
                );

            propSet.RequestedBodyType = BodyType.HTML;

            EmailMessage msg = EmailMessage.Bind(_exchangeService, id, propSet);

            return(msg);
        }
        private void ReceiveEmailFromServer(ExchangeService service)
        {
            try
            {
                //创建过滤器, 条件为邮件未读.
                ItemView view = new ItemView(999);
                view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.IsRead);
                SearchFilter            filter      = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
                FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox,
                                                                        filter,
                                                                        view);

                foreach (Item item in findResults.Items)
                {
                    EmailMessage email = EmailMessage.Bind(service, item.Id);
                    if (!email.IsRead)
                    {
                        LoggerHelper.Logger.Info(email.Body);
                        //标记为已读
                        email.IsRead = true;
                        //将对邮件的改动提交到服务器
                        email.Update(ConflictResolutionMode.AlwaysOverwrite);
                        Object _lock = new Object();
                        lock (_lock)
                        {
                            DownLoadEmail(email.Subject, email.Body, ((System.Net.NetworkCredential)((Microsoft.Exchange.WebServices.Data.WebCredentials)service.Credentials).Credentials).UserName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Logger.Error(ex, "ReceiveEmailFromServer Error");
            }
        }
Exemple #14
0
        private void Fill_Email_ListView()
        {
            ConnectToExchangeServer();
            TimeSpan ts   = new TimeSpan(0, -1, 0, 0);
            DateTime date = DateTime.Now.Add(ts);

            //SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);

            if (exchange != null)
            {
                //FindItemsResults<Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));
                FindItemsResults <Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox, new ItemView(50));

                foreach (Item item in findResults)
                {
                    EmailMessage message  = EmailMessage.Bind(exchange, item.Id);
                    ListViewItem listitem = new ListViewItem(new[]
                    {
                        message.DateTimeReceived.ToString(), message.From.Name.ToString() + "(" + message.From.Address.ToString() + ")", message.Subject, ((message.HasAttachments) ? "Yes" : "No"), message.Id.ToString()
                    });
                    lstMsg.Items.Add(listitem);
                }
                if (findResults.Items.Count <= 0)
                {
                    lstMsg.Items.Add("No Messages found!!");
                }
            }
        }
        private void listView1_Click(object sender, EventArgs e)
        {
            var msgId = listView1.SelectedItems[0].SubItems[4].Text;

            if (msgId == null)
            {
                throw new ArgumentNullException(nameof(msgId));
            }
            //MessageBox.Show(id);
            if (_exchange == null)
            {
                return;
            }
            var message = EmailMessage.Bind(_exchange, new ItemId(msgId));

            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            textBox1.ResetText();
            textBox1.Text = $@"To {message.DisplayTo}
Cc {message.DisplayCc}
{message.Body.Text}";
            textBox2.ResetText();
            button1.Text = "Reply";
        }
        public List <EmailMessage> GetLastEmails(ExchangeService client)
        {
            FindItemsResults <Item> emailItems = client.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
            var emails = emailItems.Select(item => EmailMessage.Bind(client, item.Id)).ToList();

            return(emails);
        }
Exemple #17
0
        private static void readMail(ExchangeService service)
        {
            //var items = service.FindItems(
            //    //Find Mails from Inbox of the given Mailbox
            //    new FolderId(WellKnownFolderName.Inbox, new Mailbox(ConfigurationManager.AppSettings["MailBox"].ToString())),
            //    //Filter criterion
            //    new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter[] {
            //       new SearchFilter.ContainsSubstring(ItemSchema.Subject, ConfigurationManager.AppSettings["ValidEmailIdentifier"].ToString()),
            //       new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)
            //    }),

            //    //View Size as 15
            //    new ItemView(15));

            var items = service.FindItems(
                //Find Mails from Inbox of the given Mailbox
                new FolderId(WellKnownFolderName.Inbox),
                //View Size as 15
                new ItemView(15));

            foreach (EmailMessage msg in items)
            {
                //Retrieve Additional data for Email
                EmailMessage message = EmailMessage.Bind(service,
                                                         (EmailMessage.Bind(service, msg.Id)).Id,
                                                         new PropertySet(BasePropertySet.FirstClassProperties,
                                                                         new ExtendedPropertyDefinition(0x1013, MapiPropertyType.Binary)));

                Console.Write(message.Subject);
            }
        }
        /// <summary>
        /// Read email attachments from email message by partucular item id
        /// </summary>
        /// <param name="emailItem"></param>
        /// <returns></returns>
        private async Task <EmailItem> ReadEmailAttachment(Item emailItem)
        {
            List <EmailAdditionalContent> emailAdditionalContents = new List <EmailAdditionalContent>();
            EmailMessage message = await EmailMessage.Bind(_exchangeServices.ExchangeService, emailItem.Id,
                                                           new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));

            foreach (Attachment attachment in message.Attachments)
            {
                if (attachment is FileAttachment fileAttachment)
                {
                    await fileAttachment.Load();

                    emailAdditionalContents.Add(new EmailAdditionalContent
                    {
                        ContentType   = fileAttachment.ContentType,
                        ContentSource = fileAttachment.Content,
                        ContentName   = fileAttachment.Name
                    });
                }
            }

            await emailItem.Load();

            message.IsRead = true;
            await message.Update(ConflictResolutionMode.AlwaysOverwrite);

            return(new EmailItem
            {
                EmailBody = emailItem.Body.Text,
                EmailSubject = emailItem.Subject,
                EmailAdditionalContents = emailAdditionalContents
            });
        }
Exemple #19
0
        /// <summary>
        /// Obtener un adjunto de un Email
        /// </summary>
        /// <param name="idEmail">Identificador del Email</param>
        /// <param name="idAttach">Identificador del Adjunto</param>
        /// <returns></returns>
        public EmailAttachDTO ObtenerAttach(string idEmail, string idAttach)
        {
            PropertySet props = new PropertySet(EmailMessageSchema.Attachments);
            var         email = EmailMessage.Bind(exchange, idEmail, props);

            return(new EmailAttachDTO(email.Attachments.Where(x => x.Id == idAttach).FirstOrDefault(), true));
        }
Exemple #20
0
        public void MarkAsRead(EmailMessageItem message)
        {
            var emailMessage = EmailMessage.Bind(_exchangeService, message.MessageId);

            emailMessage.IsRead = true;
            emailMessage.Update(ConflictResolutionMode.AlwaysOverwrite);
        }
Exemple #21
0
        //gavdcodeend 05

        //gavdcodebegin 06
        static void ForwardEmail(ExchangeService ExService)
        {
            SearchFilter myFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(
                    EmailMessageSchema.Subject,
                    "Email to forward"));
            ItemView myView = new ItemView(1);
            FindItemsResults <Item> findResults = ExService.FindItems(
                WellKnownFolderName.Inbox, myFilter, myView);

            ItemId myEmailId = null;

            foreach (Item oneItem in findResults)
            {
                myEmailId = oneItem.Id;
            }

            EmailMessage emailToReply = EmailMessage.Bind(ExService, myEmailId);

            EmailAddress[] forwardAddresses = new EmailAddress[1];
            forwardAddresses[0] = new EmailAddress("*****@*****.**");
            string myForward = "Forward body";

            emailToReply.Forward(myForward, forwardAddresses);
        }
Exemple #22
0
        //gavdcodeend 10

        //gavdcodebegin 11
        static void EntityExtractionFromEmail(ExchangeService ExService)
        {
            SearchFilter myFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(
                    EmailMessageSchema.Subject,
                    "Entity extraction email"));
            ItemView myView = new ItemView(1);
            FindItemsResults <Item> findResults = ExService.FindItems(
                WellKnownFolderName.Inbox, myFilter, myView);

            ItemId myEmailId = null;

            foreach (Item oneItem in findResults)
            {
                myEmailId = oneItem.Id;
            }

            PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly,
                                                    ItemSchema.EntityExtractionResult);
            Item emailWithEntities =
                EmailMessage.Bind(ExService, myEmailId, myPropSet);

            if (emailWithEntities.EntityExtractionResult != null)
            {
                if (emailWithEntities.EntityExtractionResult.MeetingSuggestions != null)
                {
                    Console.WriteLine("Entity Meetings");
                    foreach (MeetingSuggestion oneMeeting in
                             emailWithEntities.EntityExtractionResult.MeetingSuggestions)
                    {
                        Console.WriteLine("Meeting: " + oneMeeting.MeetingString);
                    }
                    Console.WriteLine(Environment.NewLine);
                }

                if (emailWithEntities.EntityExtractionResult.EmailAddresses != null)
                {
                    Console.WriteLine("Entity Emails");
                    foreach (EmailAddressEntity oneEmail in
                             emailWithEntities.EntityExtractionResult.EmailAddresses)
                    {
                        Console.WriteLine("Email address: " + oneEmail.EmailAddress);
                    }
                    Console.WriteLine(Environment.NewLine);
                }

                if (emailWithEntities.EntityExtractionResult.PhoneNumbers != null)
                {
                    Console.WriteLine("Entity Phones");
                    foreach (PhoneEntity onePhone in
                             emailWithEntities.EntityExtractionResult.PhoneNumbers)
                    {
                        Console.WriteLine("Phone: " + onePhone.PhoneString);
                    }
                    Console.WriteLine(Environment.NewLine);
                }
            }
        }
Exemple #23
0
        public void Execute(IActivityRequest request, IActivityResponse response)
        {
            userName        = settings.UserName;
            password        = settings.Password;
            domain          = settings.Domain;
            serviceURL      = settings.ServiceUrl;
            exchangeVersion = settings.ExchangeVersion;

            emailID = request.Inputs["Email ID"].AsString();


            ExchangeService service = new ExchangeService();

            switch (exchangeVersion)
            {
            case "Exchange2007_SP1":
                service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                break;

            case "Exchange2010":
                service = new ExchangeService(ExchangeVersion.Exchange2010);
                break;

            case "Exchange2010_SP1":
                service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                break;

            default:
                service = new ExchangeService();
                break;
            }

            service.Credentials = new WebCredentials(userName, password, domain);
            String AccountUrl = userName + "@" + domain;

            if (serviceURL.Equals("Autodiscover"))
            {
                service.AutodiscoverUrl(AccountUrl);
            }
            else
            {
                service.Url = new Uri(serviceURL);
            }
            PropertySet  propSet = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.MimeContent, EmailMessageSchema.IsRead);
            EmailMessage message = EmailMessage.Bind(service, emailID, propSet);

            getAttachments(message);

            if (message.HasAttachments)
            {
                response.Publish("Email Exported", message.Id.ToString());
                response.WithFiltering().PublishRange(getAttachments(message));
            }
            else
            {
                response.Publish("Email Exported", message.Id.ToString());
                response.WithFiltering().PublishRange(getAttachments(message));
            }
        }
Exemple #24
0
        public async Task DeleteMail(string mailId)
        {
            mailId = HttpUtility.UrlDecode(mailId);
            mailId = mailId.Replace(' ', '+');
            EmailMessage mail = await EmailMessage.Bind(this._exchangeService, new ItemId(mailId), PropertySet.IdOnly);

            await mail.Delete(DeleteMode.MoveToDeletedItems);
        }
Exemple #25
0
        public void LoadMessageById(string id)
        {
            _pendingAttachments = new List <string>();
            var ps = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments);

            ps.RequestedBodyType = BodyType.Text;
            CurrentMessage       = new MailMessage(EmailMessage.Bind(_service, new ItemId(id), ps));
        }
Exemple #26
0
        public void Reply(EmailMessageItem message, SalesEstimator salesEstimator)
        {
            var emailMessage = EmailMessage.Bind(_exchangeService, message.MessageId);

            var body = GetReplyBody(message, salesEstimator);

            emailMessage.Forward(body, emailMessage.From);
        }
Exemple #27
0
        public void ReplyWithException(EmailMessageItem message, Exception exception)
        {
            var emailMessage = EmailMessage.Bind(_exchangeService, message.MessageId);

            var body = exception.Message;

            emailMessage.Forward(body, emailMessage.From);
        }
Exemple #28
0
        public IList <Attachment> GetEmailAttachments(EmailMessageItem message)
        {
            var propertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments);

            var emailMessage = EmailMessage.Bind(_exchangeService, message.MessageId, propertySet);

            return(emailMessage.Attachments.ToList());
        }
Exemple #29
0
        static void Main(string[] args)
        {
            ExchangeService _exchangeService            = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
            string          _exchangeDomainUser         = ConfigurationManager.AppSettings["exchangeDomainUser"];
            string          _exchangeDomainUserPassword = ConfigurationManager.AppSettings["exchangeDomainUserPassword"];
            string          _exchangeUrl         = ConfigurationManager.AppSettings["exchangeUrl"];
            string          _exchangeMailSubject = ConfigurationManager.AppSettings["exchangeMailSubject"];

            try
            {
                _exchangeService = new ExchangeService
                {
                    Credentials = new WebCredentials(_exchangeDomainUser, _exchangeDomainUserPassword)
                };

                // This is the office365 webservice URL
                _exchangeService.Url = new Uri(_exchangeUrl);

                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

                // create archive folder
                FolderId folderId = CreateArchiveFolder(_exchangeService);

                // file download and move email to archive folder
                List <SearchFilter> searchFilterCollection = new List <SearchFilter>();
                searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, _exchangeMailSubject));
                SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
                ItemView     view         = new ItemView(50);
                view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);
                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
                view.Traversal = ItemTraversal.Shallow;
                FindItemsResults <Item> findResults = _exchangeService.FindItems(WellKnownFolderName.Inbox, searchFilter, view);

                if (findResults != null && findResults.Items != null && findResults.Items.Count > 0)
                {
                    foreach (EmailMessage item in findResults)
                    {
                        EmailMessage message = EmailMessage.Bind(_exchangeService, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
                        foreach (Attachment attachment in message.Attachments)
                        {
                            if (attachment is FileAttachment)
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                fileAttachment.Load(@"D:\\Files\\" + fileAttachment.Name);
                            }
                        }

                        // move mail to archive folder
                        item.Move(folderId);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("new ExchangeService failed");
                return;
            }
        }
Exemple #30
0
        public void ResendExceptionToAdmin(EmailMessageItem message, Exception exception)
        {
            var emailMessage = EmailMessage.Bind(_exchangeService, message.MessageId);

            var body   = String.Format("Message <strong>'{0}'</strong> processing error.<br/>{1}", message.Subject, exception);
            var emails = _settingsService.ExchangeAdminEmails.Select(n => new EmailAddress(n));

            emailMessage.Forward(body, emails);
        }