private static bool ShouldConsiderMessage(EmailMessage message, string[] recipients) { if (message == null) { return(false); } // Load additional properties for the current EmailMessage item message.Load(); // If no recipients were mentioned, it means process all incoming emails if (!recipients.Any()) { return(true); } var msg = GetToCCList(message); // If the recipient is in either the To or CC lines, then this message should be considered return(recipients.Any(recipient => EmailAddressesMatch(msg.ToAddresses, recipient) || EmailAddressesMatch(msg.ToNames, recipient) || EmailAddressesMatch(msg.CcAddresses, recipient) || EmailAddressesMatch(msg.CcNames, recipient))); }
private static EmailMessageWrapper GetEmailMessageWrapper(EmailMessage email, Guid exchangeConfigurationId) { var receivedDate = DateTime.UtcNow; email.Load(new PropertySet(ItemSchema.DateTimeReceived, EmailMessageSchema.ReceivedBy)); try { receivedDate = email.DateTimeReceived; } catch { try { receivedDate = email.DateTimeSent; } catch { System.Diagnostics.Debug.WriteLine(new Exception("Cannot retrieve date from email")); } } return(new EmailMessageWrapper { ExchangeConfigurationId = exchangeConfigurationId, ItemId = email.Id.UniqueId, EmlContent = GetEmlContent(email), ReceivedDate = receivedDate }); }
public EWSIncomingMessage(EmailMessage message, bool useConversationGuidOnly = false) { _message = message; _useConversationGuidOnly = useConversationGuidOnly; message.Load(new PropertySet( ItemSchema.Subject, ItemSchema.Body, EWSExtendedProperty.PidTagBody, EWSExtendedProperty.PidTagConversationId, EmailMessageSchema.ConversationIndex, EmailMessageSchema.Sender, EmailMessageSchema.From, EmailMessageSchema.ToRecipients, EmailMessageSchema.CcRecipients, ItemSchema.MimeContent, ItemSchema.DateTimeReceived, ItemSchema.DateTimeSent, EmailMessageSchema.ConversationTopic, ItemSchema.Attachments, ItemSchema.HasAttachments, MeetingRequestSchema.Location, MeetingRequestSchema.Start, MeetingRequestSchema.End ) { RequestedBodyType = BodyType.HTML }); // Specify Exchange should convert native body format to HTML before returning message.TryGetProperty(EWSExtendedProperty.PidTagConversationId, out _conversationId); Attachments = BuildAttachmentList(message); }
private List <string> GetAttachmentRic(string keyWord, string downloadPath) { List <string> list = new List <string>(); try { query = new EWSMailSearchQuery("", emailAccount.MailAddress, emailFolder, keyWord, "", startDate, endDate); List <EmailMessage> mailList = GetEmailList(service, query, keyWord); if (mailList == null) { string msg = string.Format("email account error."); Logger.Log(msg, Logger.LogType.Error); return(null);//ric list ==null } if (mailList.Count == 0) { string msg = string.Format("no email in this account within this email folder"); Logger.Log(msg, Logger.LogType.Warning); return(list);//ric list.count==0 } EmailMessage email = mailList[0]; email.Load(); List <string> attachments = EWSMailSearchQuery.DownloadAttachments(service, email, "", "", downloadPath); return(GetRicFromFile(attachments)); } catch (Exception ex) { string msg = string.Format("execute GetRicFromIFFM() failed. msg:{0}", ex.Message); Logger.Log(msg, Logger.LogType.Error); return(list); } }
public static string getEmailMessageAsSourceForm(this EmailMessage email) { email.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.MimeContent)); MimeContent mc = email.MimeContent; return(mc.ToString()); }
public EWSIncomingMessage(EmailMessage message, bool useConversationGuidOnly = false) { _message = message; _useConversationGuidOnly = useConversationGuidOnly; // Extended property for PidTagConversationId, which is the GUID portion of the ConversationIndex // See https://msdn.microsoft.com/en-us/library/cc433490(v=EXCHG.80).aspx and // https://msdn.microsoft.com/en-us/library/ee204279(v=exchg.80).aspx for more information ExtendedPropertyDefinition conversationId = new ExtendedPropertyDefinition(PidTagConversationIdTag, MapiPropertyType.Binary); message.Load(new PropertySet( ItemSchema.Subject, ItemSchema.Body, EmailMessageSchema.ConversationIndex, conversationId, EmailMessageSchema.Sender, EmailMessageSchema.From, EmailMessageSchema.ToRecipients, EmailMessageSchema.CcRecipients, ItemSchema.MimeContent, ItemSchema.DateTimeReceived, ItemSchema.DateTimeSent, EmailMessageSchema.ConversationTopic, ItemSchema.Attachments, ItemSchema.HasAttachments, MeetingRequestSchema.Location, MeetingRequestSchema.Start, MeetingRequestSchema.End )); message.TryGetProperty(conversationId, out _conversationId); Attachments = BuildAttachmentList(message); }
public EWSIncomingMessage(EmailMessage message) { _message = message; message.Load(new PropertySet( ItemSchema.Subject, ItemSchema.Body, EmailMessageSchema.ConversationIndex, EmailMessageSchema.Sender, EmailMessageSchema.From, EmailMessageSchema.ToRecipients, EmailMessageSchema.CcRecipients, ItemSchema.MimeContent, ItemSchema.DateTimeReceived, ItemSchema.DateTimeSent, EmailMessageSchema.ConversationTopic, ItemSchema.Attachments, ItemSchema.HasAttachments, MeetingRequestSchema.Location, MeetingRequestSchema.Start, MeetingRequestSchema.End )); Attachments = BuildAttachmentList(message); }
private static MailConversations extractItems(FindItemsResults <Item> findResults) { log.Info("searching social medial mails in folder" + subFolderName); MailConversations mc = new MailConversations(); if (findResults.TotalCount > 0) { Dictionary <string, List <EmailMessage> > dict = mc.conversations; foreach (Item myItem in findResults.Items) { //myItem.Load(); PropertySet propSet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, EmailMessageSchema.IsRead); EmailMessage mail = EmailMessage.Bind(service, myItem.Id, propSet); mail.Load(); //if the conversation is not in the dict, then create a new list and add to dict if (!dict.ContainsKey(mail.ConversationId)) { List <EmailMessage> list = new List <EmailMessage>(); list.Add(mail); dict.Add(mail.ConversationId, list); } //if the conversation is already in the dict, then get it and add mail to the list else { dict[mail.ConversationId].Add(mail); } } /** * StreamWriter sw = new StreamWriter(@"c:\test\test\2.html"); * foreach (string key in dict.Keys) * { * //sort the mail of each conversation to find out the latest reply * dict[key].OrderBy(o => string.Join("", o.ConversationIndex)).ToList(); * foreach (EmailMessage mail in dict[key]) * { * sw.WriteLine(mail.Body); * sw.WriteLine("===============================" + mail.ConversationId + "==========" + mail.DateTimeReceived + "====================" + string.Join("", mail.ConversationIndex) + "=================="); * } * //sw.WriteLine("===============================" + dict[key][0].ConversationId + "==========" + dict[key][0].DateTimeReceived + "====================" + string.Join("", dict[key][0].ConversationIndex) + "=================="); * * } * * sw.Close(); * * **/ return(mc); } //if no result was found else { return(null); } }
public void Save(EmailMessage email, string folderName) { email.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.TextBody)); DateTime mailDate = Convert.ToDateTime(email.DateTimeReceived); DateTime date = Convert.ToDateTime(DateTime.Now.ToString()); double day = (date - mailDate).TotalDays; //do something with this email data. }
public MailRequest(EmailMessage msg) { this.From = msg.From.Address; this.To = msg.ToRecipients.First().Address; this.Subject = msg.Subject; this.Body = msg.Body; this.OriginalMessage = msg; msg.Load(new PropertySet(ItemSchema.MimeContent)); this.FileFormat = msg.MimeContent.Content; }
private bool FetchMessage(EmailMessage msg, PropertySet ptySet) { try { msg.Load(ptySet); } catch (Exception e) { HandleError(e, 1); return false; } return true; }
/// <summary> /// Demonstrates three ways to get file attachments and how to get an item attachment. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> private static void GetAttachments(ExchangeService service) { // Return a single item. ItemView view = new ItemView(1); string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email"; // Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS. FindItemsResults <Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view); if (results.TotalCount > 0) { EmailMessage email = results.Items[0] as EmailMessage; // Request all the attachments on the email message. This results in a GetItem operation call to EWS. email.Load(new PropertySet(EmailMessageSchema.Attachments)); foreach (Attachment attachment in email.Attachments) { if (attachment is FileAttachment) { FileAttachment fileAttachment = attachment as FileAttachment; // Load the file attachment into memory. This gives you access to the attachment content, which // is a byte array that you can use to attach this file to another item. This results in a GetAttachment operation // call to EWS. fileAttachment.Load(); Console.WriteLine("Load a file attachment with a name = " + fileAttachment.Name); // Load attachment contents into a file. This results in a GetAttachment operation call to EWS. fileAttachment.Load("C:\\temp\\" + fileAttachment.Name); // Put attachment contents into a stream. using (FileStream theStream = new FileStream("C:\\temp\\Stream_" + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { //This results in a GetAttachment operation call to EWS. fileAttachment.Load(theStream); } } else // Attachment is an item attachment. { ItemAttachment itemAttachment = attachment as ItemAttachment; // Load the item attachment properties. This results in a GetAttachment operation call to EWS. itemAttachment.Load(); Console.WriteLine("Loaded an item attachment with Subject = " + itemAttachment.Item.Subject); } } } }
public IAttachment GetAsAttachment(IMailItem model) { EmailMessage message = GetEmailMessage(model); string title = message.Subject; message.Load(new PropertySet(ItemSchema.MimeContent)); using (MemoryStream ms = new MemoryStream()) { MimeContent mc = message.MimeContent; ms.Write(mc.Content, 0, mc.Content.Length); return(Factory.ToAttachment(title, ms.ToArray())); } }
private bool MakeResponseMessage(ResponseMessageType oResponseMessageType) { bool bRet = false; MessageBody oMessageBody = new MessageBody("----\r\n"); ResponseMessage oResponseMessage = null; string sWindowTitle = string.Empty; try { if (oResponseMessageType == ResponseMessageType.Reply) { _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. oResponseMessage = _EmailMessage.CreateReply(false); sWindowTitle = "Reply Message"; } if (oResponseMessageType == ResponseMessageType.ReplyAll) { _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. oResponseMessage = _EmailMessage.CreateReply(true); sWindowTitle = "Reply All Message"; } if (oResponseMessageType == ResponseMessageType.Forward) { _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. oResponseMessage = _EmailMessage.CreateForward(); sWindowTitle = "Forward Message"; } //oResponseMessage.BodyPrefix = "===========\r\n"; // Save as drafts AND set as new current message. _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. _EmailMessage = oResponseMessage.Save(WellKnownFolderName.Drafts); _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. _EmailMessage.Load(); SetFormFromMessage(_EmailMessage, true, true, false); bRet = true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error creating message"); bRet = false; } return(bRet); }
private Email GetEmailEntity(EmailMessage item) { Email email = new Email(); item.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.TextBody)); // item.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Body)); email.Subject = item.Subject; email.Body = item.TextBody.ToString(); email.BodyHtml = item.Body.Text; email.From = item.From.Address.ToString(); email.To = item.DisplayTo.ToString(); email.CC = item.DisplayCc; email.DateTimeReceived = item.DateTimeReceived; return(email); }
public void SendResponse(EmailMessage originalMessage, string body) { originalMessage.Load(); Logger.Debug(new LogInfo(MethodBase.GetCurrentMethod(), "DEB", string.Format("Notifica evento al mittente {0}", originalMessage.Sender))); // Occorre "riagganciare" il messaggio alla casella // per farlo ci basta sapere l'id var propSet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.LastModifiedTime); // GetItem call to EWS. EmailMessage reply = EmailMessage.Bind(this.service, originalMessage.Id, propSet); reply.Reply(Mailify(body), true); //Console.WriteLine("Processato " + mailInput.EmailMessage.Subject); }
/// <summary> /// Export the eamil messges form the specific search folder. /// </summary> private static void ExportEmailMessages(SearchFolder searchFolder, String filePath) { if (searchFolder == null) { return; } String[] invalidStings = { "\\", ",", ":", "*", "?", "\"", "<", ">", "|" }; PropertySet itemPorpertySet = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.MimeContent); const Int32 pageSize = 50; ItemView itemView = new ItemView(pageSize); FindItemsResults <Item> findResults = null; do { findResults = searchFolder.FindItems(itemView); foreach (Item item in findResults.Items) { if (item is EmailMessage) { EmailMessage email = item as EmailMessage; email.Load(itemPorpertySet); Byte[] content = email.MimeContent.Content; String fileName = email.Subject; // Replace all the invaild strings. foreach (String str in invalidStings) { fileName = fileName.Replace(str, ""); } // Export the emails to the .eml files. fileName = Path.Combine(filePath, fileName + ".eml"); File.WriteAllBytes(fileName, content); Console.WriteLine("Export the email:{0}", email.Subject); } } itemView.Offset += pageSize; } while (findResults.MoreAvailable); }
public void loadMail(FindItemsResults <Item> findResults, Item item, ExchangeService service, Program prog) { //foreach (Item item in findResults.Items) //{ EmailMessage message = EmailMessage.Bind(service, item.Id, PropertySet.FirstClassProperties); message.Load(); this.mFrom = message.From.ToString(); this.mMailboxAddress = message.From.Address; this.mMailboxName = message.From.Name; //if(mail.mMailboxAddress == "*****@*****.**" || mail.mMailboxName == "Omar Hassan") { mail.mIsAuthority = true; } if (this.mMailboxAddress == "*****@*****.**") { this.mIsAuthority = true; } else { this.mIsAuthority = false; } //if (this.mMailboxAddress == "*****@*****.**") //{ // EmailErrors ee = new EmailErrors(prog); // ee.sendMilestoneErrorEmail(); //} //string[] recipients = ((Microsoft.Exchange.WebServices.Data.EmailAddressCollection)item[EmailMessageSchema.ToRecipients]).Select(recipient => recipient.Address).ToArray(); Console.WriteLine("the address is: " + this.mFrom); Console.WriteLine("the mailbox type is: " + message.From.MailboxType); Console.WriteLine("the mailbox address is: " + message.From.Address); Console.WriteLine("the mailbox name is: " + message.From.Name); this.mBody = message.Body.Text; this.mSubject = message.Subject; string dateAndTimeSent = message.DateTimeSent.ToString(); this.mDateAndTimeSent = message.DateTimeSent.ToString(); prog.setMDateAndTimeSent(dateAndTimeSent); Console.WriteLine("the date and time sent is: " + this.mDateAndTimeSent); Console.WriteLine("the email read is: " + this.mSubject); message.IsRead = true; message.Update(ConflictResolutionMode.AlwaysOverwrite); //EmailMessage email = (EmailMessage)item; //Do other stuff //} }
public MailMsg(EmailMessage msg, string user) { this._User = user; this._id = msg.Id.ToString(); timestamp = msg.DateTimeSent; this._Subject = msg.Subject; this._Body = msg.Body; if (msg.HasAttachments) { //we will add all attachements to a list List <Attachement> oList = new List <Attachement>(); //load all attachements msg.Load(new Microsoft.Exchange.WebServices.Data.PropertySet(Microsoft.Exchange.WebServices.Data.EmailMessageSchema.Attachments)); foreach (Microsoft.Exchange.WebServices.Data.Attachment att in msg.Attachments) { if (att is Microsoft.Exchange.WebServices.Data.FileAttachment) { //load the attachement Microsoft.Exchange.WebServices.Data.FileAttachment fileAttachment = att as Microsoft.Exchange.WebServices.Data.FileAttachment; //load into memory stream, seems the only stream supported System.IO.MemoryStream ms = new System.IO.MemoryStream(att.Size); fileAttachment.Load(ms);//blocks some time ms.Position = 0; oList.Add(new Attachement(ms, fileAttachment.Name)); ms.Close(); } } /* * foreach (Attachment a in msg.Attachments) * { * if (a is Microsoft.Exchange.WebServices.Data.FileAttachment) * { * FileAttachment fa = a as FileAttachment; * System.IO.MemoryStream ms=new System.IO.MemoryStream(fa.Size); * fa.Load(ms); * oList.Add(new Attachement(ms, fa.Name)); * } * } */ this._Attachements = oList.ToArray(); this.attList.AddRange(oList); } }
/// <summary> /// Demonstrates three ways to delete attachments from an item. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> private static void DeleteAttachments(ExchangeService service) { // Return a single item. ItemView view = new ItemView(1); string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email"; // Find the first email message in the Inbox that has attachments and a subject that contains 'Message with Attachments'. // This results in a FindItem call to EWS. FindItemsResults <Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view); if (results.TotalCount > 0) { EmailMessage email = results.Items[0] as EmailMessage; // Get all the attachments on the email message. This results in a GetAttachment call to EWS. email.Load(new PropertySet(EmailMessageSchema.Attachments)); // Remove attachment by index position. if (email.Attachments.Count > 0) { email.Attachments.RemoveAt(0); } // Remove attachments by file name. foreach (Attachment attachment in email.Attachments) { if (attachment.Name.ToUpper() == "THIRDATTACHMENT.JPG") { email.Attachments.Remove(attachment); break; } } // Remove all attachments from an item. email.Attachments.Clear(); // Save the updated message. This results in a DeleteAttachment operation call to EWS. // If any other properties are updated in addition to the attachments, // an UpdateItem operation call to EWS will occur. email.Update(ConflictResolutionMode.AlwaysOverwrite); } }
/// <summary> /// Attachements Extract from EmailMessage /// </summary> /// <param name="email">The Email Message</param> /// <param name="folder">The specific email folder</param> public void AttachementsEx(EmailMessage email, string folder) { if (email == null || string.IsNullOrEmpty(folder)) { return; } email.Load(new PropertySet(EmailMessageSchema.Attachments)); foreach (Attachment attachment in email.Attachments) { if (attachment is FileAttachment) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); string fullPath = string.Format("{0}\\{1}", folder, fileAttachment.Name); using (FileStream theStream = new FileStream(fullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { fileAttachment.Load(theStream); } } } }
/// <summary> /// ReadEmailTolistRicChain /// </summary> /// <param name="listRicChain"></param> /// <param name="strPattern">pattern</param> /// <param name="strEmailKeyWord">Email title</param> private void ReadEmailTolistRicChain(List <string> listRicChain, string strPattern, string strEmailKeyWord) { try { EWSMailSearchQuery query = new EWSMailSearchQuery("", mailAdress, mailFolder, strEmailKeyWord, "", startDate, endDate); List <EmailMessage> mailList = null; for (int i = 0; i < 5; i++) { try { mailList = EWSMailSearchQuery.SearchMail(service, query); break; } catch { Thread.Sleep(5000); if (i == 4) { throw; } } } if (mailList.Count > 0) { isExistEmail = true; EmailMessage mail = mailList[0]; mail.Load(); strEmailRicChain = TWHelper.ClearHtmlTags(mail.Body.ToString()); Regex regex = new Regex(strPattern); MatchCollection matches = regex.Matches(strEmailRicChain); foreach (Match match in matches) { listRicChain.Add(match.Groups["RIC"].Value); } } } catch (Exception ex) { Logger.Log("Get Data from mail failed. Ex: " + ex.Message); } }
private List <string> GetRicFromEmailBody(string keyWord, string pattern) { List <string> list = new List <string>(); try { query = new EWSMailSearchQuery("", emailAccount.MailAddress, emailFolder, keyWord, "", startDate, endDate); List <EmailMessage> mailList = GetEmailList(service, query, keyWord); if (mailList == null) { string msg = string.Format("email account error."); Logger.Log(msg, Logger.LogType.Error); return(null);//ric list ==null } if (mailList.Count == 0) { string msg = string.Format("no email in this account within this email folder"); Logger.Log(msg, Logger.LogType.Warning); return(list);//ric list.count==0 } EmailMessage email = mailList[0]; email.Load(); string body = email.Body.ToString(); return(GetRicIFFM(body, pattern)); } catch (Exception ex) { string msg = string.Format("execute GetRicFromIFFM() failed. msg:{0}", ex.Message); Logger.Log(msg, Logger.LogType.Error); return(list); } }
//thread to get all emails public static void _getMails(object param) { helpers.addLog("_getMails() started..."); ews _ews = (ews)param; //need an instance _ews.OnStateChanged(new StatusEventArgs(StatusType.busy, "_getMails() started...")); const int chunkSize = 50; try { PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; //request plain text body //blocking call ItemView view = new ItemView(chunkSize); view.PropertySet = itempropertyset; view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending); /* * private static void GetAttachments(ExchangeService service) * { * // Return a single item. * ItemView view = new ItemView(1); * * string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email"; * * // Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS. * FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view); * * if (results.TotalCount > 0) * { * EmailMessage email = results.Items[0] as EmailMessage; */ FindItemsResults <Item> findResults; do { //findResults = service.FindItems(WellKnownFolderName.Inbox, view); SearchFilter.SearchFilterCollection filterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And); filterCollection.Add(new SearchFilter.Not(new SearchFilter.ContainsSubstring(ItemSchema.Subject, sMailHasAlreadyProcessed))); filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, helpers.filterSubject)); filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Attachments, helpers.filterAttachement)); findResults = _ews._service.FindItems(WellKnownFolderName.Inbox, filterCollection, view); _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: found " + findResults.Items.Count + " items in inbox")); foreach (Item item in findResults.Items) { helpers.addLog("found item..."); if (item is EmailMessage) { EmailMessage mailmessage = item as EmailMessage; mailmessage.Load(itempropertyset); //load data from server helpers.addLog("\t is email ..."); // If the item is an e-mail message, write the sender's name. helpers.addLog(mailmessage.Sender.Name + ": " + mailmessage.Subject); _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: processing eMail " + mailmessage.Subject)); MailMsg myMailMsg = new MailMsg(mailmessage, _ews._userData.sUser); // Bind to an existing message using its unique identifier. //EmailMessage message = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId)); int iRet = _ews._licenseMail.processMail(myMailMsg); //change subject? // Bind to the existing item, using the ItemId. This method call results in a GetItem call to EWS. Item myItem = Item.Bind(_ews._service, item.Id as ItemId); myItem.Load(); // Update the Subject of the email. myItem.Subject += "[processed]"; // Save the updated email. This method call results in an UpdateItem call to EWS. myItem.Update(ConflictResolutionMode.AlwaysOverwrite); _ews.OnStateChanged(new StatusEventArgs(StatusType.license_mail, "processed " + iRet.ToString())); } } view.Offset += chunkSize; } while (findResults.MoreAvailable && _ews._bRunThread); _ews.OnStateChanged(new StatusEventArgs(StatusType.idle, "readmail done")); } catch (ThreadAbortException ex) { helpers.addLog("ThreadAbortException: " + ex.Message); } catch (Exception ex) { helpers.addLog("Exception: " + ex.Message); _ews.OnStateChanged(new StatusEventArgs(StatusType.error, "readmail exception: " + ex.Message)); } helpers.addLog("_getMails() ended"); _ews.startPull(); }
private void FilllistEXLFromEmail() { try { service = EWSUtility.CreateService(new System.Net.NetworkCredential(accountName, password, domain), new Uri(@"https://apac.mail.erf.thomson.com/EWS/Exchange.asmx")); EWSMailSearchQuery query; if (string.IsNullOrEmpty(emailDate)) { query = new EWSMailSearchQuery("", mailAdress, mailFolder, "TWWNT_DROP_IFFM Expired RICs Housekeeping Report for TWWNT_DROP", "", dateTime.AddHours(-dateTime.Hour).AddMinutes(-dateTime.Minute), dateTime); } else { startTime = Convert.ToDateTime(emailDate); endTime = startTime.AddDays(+1); query = new EWSMailSearchQuery("", mailAdress, mailFolder, "TWWNT_DROP_IFFM Expired RICs Housekeeping Report for TWWNT_DROP", "", startTime, endTime); } List <EmailMessage> mailList = null; for (int i = 0; i < 5; i++) { try { mailList = EWSMailSearchQuery.SearchMail(service, query); break; } catch { Thread.Sleep(5000); if (i == 4) { throw; } } } if (mailList.Count > 0) { string emailString = string.Empty; EmailMessage mail = mailList[0]; mail.Load(); emailString = TWHelper.ClearHtmlTags(mail.Body.ToString()); string[] emailEXL = emailString.Replace("EXL", "~").Split('~'); foreach (string email in emailEXL.Where(email => email.Trim().StartsWith("("))) { List <string> listTmp; string tmp = email.Substring(email.IndexOf("(") + 1, email.IndexOf(")") - 2).Trim(); switch (tmp) { case "TAIW_INX_WNT": listTmp = new List <string> { tmp }; RegexPattern(email, listTmp); break; case "TAIW_EQLB_WNT": listTmp = new List <string> { tmp }; RegexPattern(email, listTmp); break; case "TAIW_CBBC": listTmp = new List <string> { tmp }; RegexPattern(email, listTmp); break; case "OTCTWS_WNT": listTmp = new List <string> { tmp }; RegexPattern(email, listTmp); break; case "OTCTWS_INX_WNT": listTmp = new List <string> { tmp }; RegexPattern(email, listTmp); break; } } } else { MessageBox.Show("No email of TWWNT_DROP_IFFM in Outlook!"); } } catch (Exception ex) { Logger.Log("Get Data from mail failed. Ex: " + ex.Message + "Try To Execute {EWSMailSearchQuery.SearchMail(service, query)} 5 times"); } }
static async System.Threading.Tasks.Task Main(string[] args) { using (log = new StreamWriter("BackOfficeUA.log", true, Encoding.GetEncoding(1251))) { try { WebClient wc = new WebClient { Credentials = new NetworkCredential("techadmin", "Bpgjldsgjldthnf77!", "AM"), }; LastWorkDate = wc.DownloadString("http://assetsmgr/home/GetLastWorkDate"); ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); service.UseDefaultCredentials = false; service.Credentials = new NetworkCredential("BackOfficeUA", "QWESZ123@"); service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback); JavaScriptSerializer jss = new JavaScriptSerializer(); var cfg = new EFolder[] { }; var FileName = "BackOfficeUA.dat"; if (File.Exists(FileName)) { using (StreamReader sr = new StreamReader(FileName, Encoding.GetEncoding(1251))) { cfg = jss.Deserialize <EFolder[]>(sr.ReadToEnd()); } } foreach (var ef in cfg) //for (int i= cfg.Length-1; i>=0;i--) { Console.WriteLine(ef.DisplayName); FolderView view = new FolderView(1); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName); SearchFilter searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, ef.DisplayName); FindFoldersResults findResults = service.FindFolders(new FolderId(WellKnownFolderName.Inbox), searchFilter, view); if (findResults.TotalCount == 1) { FolderId id1 = findResults.Folders[0].Id; bool moreChangesAvailable = false; do { ChangeCollection <ItemChange> icc = service.SyncFolderItems(id1, PropertySet.IdOnly, null, 512, SyncFolderItemsScope.NormalItems, ef.SyncState); if (icc.Count > 0) { foreach (ItemChange ic in icc) { if (ic.ChangeType == ChangeType.Create) { EmailMessage e = ic.Item as EmailMessage; e.Load(new PropertySet(EmailMessageSchema.Attachments, EmailMessageSchema.From, EmailMessageSchema.Subject, EmailMessageSchema.IsRead)); foreach (Attachment attachment in e.Attachments) { if (attachment is FileAttachment) { FileAttachment fileAttachment = attachment as FileAttachment; Console.WriteLine("File attachment name: " + fileAttachment.Name); if (e.From.Address == "*****@*****.**") { OpenFc(fileAttachment); } else if (new string[] { "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**" }.Contains(e.From.Address)) { UralsibWeb(fileAttachment); } else if (e.From.Address == "*****@*****.**") { await OpenBr(fileAttachment); } else if (e.From.Address.EndsWith("@bloomberg.net")) { Bloomberg(fileAttachment); } else if (e.From.Address == "*****@*****.**" && e.Subject.StartsWith("Broker report")) { await Bcs(fileAttachment); } else if (e.From.Address == "*****@*****.**" || e.From.Address == "*****@*****.**") { await BcsM(fileAttachment); } } } } } } ef.SyncState = icc.SyncState; moreChangesAvailable = icc.MoreChangesAvailable; using (var sw = new StreamWriter(FileName, false, Encoding.GetEncoding(1251))) { sw.WriteLine(jss.Serialize(cfg)); await sw.FlushAsync(); } }while (moreChangesAvailable); } } //log.Write(DateTime.Now); //log.Write(" "); //log.WriteLine(jss.Serialize(cfg)); } catch (Exception ex) { if (!string.IsNullOrEmpty(ex.Message)) { log.Write(DateTime.Now); log.Write(" "); log.WriteLine(ex.Message); } } } }
/// <summary> /// Demonstrates three ways to create file attachments and two different ways to create copies of an /// item and add it to an email message. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> private static void CreateAttachments(ExchangeService service) { // Create an email message. EmailMessage email = new EmailMessage(service); email.Subject = "Message with Attachments"; email.Body = "This message contains three file attachments and two item attachments."; email.ToRecipients.Add("*****@*****.**"); // This must be set on the item attachments so that they can be consumed in Outlook. ExtendedPropertyDefinition PR_MESSAGE_FLAGS_msgflag_read = new ExtendedPropertyDefinition(3591, MapiPropertyType.Integer); // Use OpenFileDialog to get the file that will be used to create file attachments. string filename; string fullfilename; Stream myStream = null; OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "All files (*.*)|*.*"; openFileDialog.InitialDirectory = "C:"; openFileDialog.Title = "Select an attachment"; openFileDialog.FilterIndex = 1; if (openFileDialog.ShowDialog() == DialogResult.OK) { try { if ((myStream = openFileDialog.OpenFile()) != null) { filename = openFileDialog.SafeFileName; fullfilename = openFileDialog.FileName; using (myStream) { #region Add file attachments // Add the file attachment to the email message by using the file name and stream. var fileAttach = email.Attachments.AddFileAttachment(filename, myStream); // Add the file attachment to the email message by using the full file name. var fileAttach2 = email.Attachments.AddFileAttachment(fullfilename); // Add the file attachment to the email message by using the full file name and the file name. var fileAttach3 = email.Attachments.AddFileAttachment(filename, fullfilename); // A fourth option is to add a file attachment by using the the file // name and byte array for the file. #endregion #region Add item attachments. // Return a single item. ItemView view = new ItemView(1); // Find the first email message in the Inbox. You will "attach" this email message to the email message you are drafting. // This results in a FindItem operation call to EWS. FindItemsResults <Item> results = service.FindItems(WellKnownFolderName.Inbox, view); // Verify that the item is an email message. if (results.Items[0] is EmailMessage) { EmailMessage msg = results.Items[0] as EmailMessage; System.Collections.ObjectModel.Collection <PropertyDefinitionBase> currentProps = msg.GetLoadedPropertyDefinitions(); currentProps.Add(EmailMessageSchema.Body); currentProps.Add(EmailMessageSchema.ToRecipients); currentProps.Add(EmailMessageSchema.CcRecipients); msg.Load(new PropertySet(currentProps)); // Attach the email message found from search to the new email message. In reality, you can't attach // existing items, you have to make a copy of the item property by property. The Item type does not // implement ICloneable. ItemAttachment <EmailMessage> itemAttachment = email.Attachments.AddItemAttachment <EmailMessage>(); itemAttachment.Name = "Item attachment based on copied property values"; itemAttachment.Item.Subject = msg.Subject; itemAttachment.Item.Body = msg.Body; foreach (EmailAddress address in msg.ToRecipients) { itemAttachment.Item.ToRecipients.Add(address); } foreach (EmailAddress address in msg.CcRecipients) { itemAttachment.Item.ToRecipients.Add(address); } // The Sent flag should be set. itemAttachment.Item.SetExtendedProperty(PR_MESSAGE_FLAGS_msgflag_read, 1); // Unfortunately, not all properties are settable, like DateTimeReceived. If the item is an email message, // you can use the MIME content, which provides a decent copy of the email message without any of the // Exchange store properties. You can add store properties to the item as well, as long // as they are writeable. msg.Load(new PropertySet(EmailMessageSchema.MimeContent)); ItemAttachment <EmailMessage> itemAttachment2 = email.Attachments.AddItemAttachment <EmailMessage>(); itemAttachment2.Name = "Item attachment based on copied MIME content"; itemAttachment2.Item.MimeContent = msg.MimeContent; // The Sent flag should be set. itemAttachment2.Item.SetExtendedProperty(PR_MESSAGE_FLAGS_msgflag_read, 1); } #endregion /* This results in two calls to EWS. The first call is the CreateItem operation, which creates the * email message in the Drafts folder and adds the attachment. The second call is a SendItem call, which sends * the email message and creates a copy in the default Sent Items folder.*/ email.SendAndSaveCopy(); } } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } }
/// <summary> /// DownloadAttachementFileFromEmail /// </summary> /// <param name="listAttachementFile">store file name</param> /// <param name="strEmailKeyWord">subject</param> /// <param name="isExistEmail">bool</param> /// <param name="isEmptyEmail">bool</param> private void GetAttachementFromEmail(List <string> listAttachementFile, string strEmailKeyWord, ref bool isExistEmail, ref bool isEmptyEmail) { try { service = MSAD.Common.OfficeUtility.EWSUtility.CreateService(new System.Net.NetworkCredential(accountName, password, domain), new Uri(@"https://apac.mail.erf.thomson.com/EWS/Exchange.asmx")); EWSMailSearchQuery query = new EWSMailSearchQuery("", mailAdress, mailFolder, strEmailKeyWord, "", startDate, endDate); List <EmailMessage> mailList = null; string strEmailContent = string.Empty; for (int i = 0; i < 5; i++) { try { mailList = EWSMailSearchQuery.SearchMail(service, query); break; } catch { Thread.Sleep(5000); if (i == 4) { throw; } } } if (mailList.Count > 0) { isExistEmail = true; string attachmentPath = Path.Combine(txtFilePath, "attachment"); EmailMessage mail = mailList[0]; if (!Directory.Exists(attachmentPath)) { Directory.CreateDirectory(attachmentPath); } else { string[] rootFiles = Directory.GetFiles(attachmentPath); foreach (string file in rootFiles) { File.Delete(file); } } mail.Load(); List <string> attachments = EWSMailSearchQuery.DownloadAttachments(service, mail, "", "", attachmentPath); if (attachments != null && attachments.Count != 0) { string dir = Path.GetDirectoryName(attachments[0]); foreach (string zipFile in attachments) { string err = null; if (!Ric.Util.ZipUtil.UnZipFile(zipFile, dir, out err)) { Logger.Log(string.Format("Error happens when unzipping the file {0}. Exception message: {1}", zipFile, err)); } } foreach (var file in Directory.GetFiles(Path.GetDirectoryName(attachments[0]), "*.xls")) { listAttachementFile.Add(file); } } else { isEmptyEmail = true; Logger.Log("Found email but no attachement"); } } else { Logger.Log("there is no email in mail box!"); } } catch (Exception ex) { Logger.Log("Get Data from mail failed. Ex: " + ex.Message); } }
/// <summary> /// ReadEmailAndGetData /// </summary> /// <param name="listRic">listRic</param> /// <param name="strPattern">regular expression</param> /// <param name="strEmailKeyWord">subject of email</param> private void ReadEmailTolistRicChain(List <string> listRic, string strPattern, string strEmailKeyWord) { try { service = EWSUtility.CreateService(new System.Net.NetworkCredential(accountName, password, domain), new Uri(@"https://apac.mail.erf.thomson.com/EWS/Exchange.asmx")); EWSMailSearchQuery query = null; query = new EWSMailSearchQuery("", mailAdress, mailFolder, strEmailKeyWord, "", startDate, endDate); List <EmailMessage> mailList = null; for (int i = 0; i < 5; i++) { try { mailList = EWSMailSearchQuery.SearchMail(service, query); break; } catch { Thread.Sleep(5000); if (i == 4) { throw; } } } if (mailList.Count > 0) { if (strEmailKeyWord.Equals("TAIFO IFFM - EDA Automation Report")) { isExistFirstEmail = true; } else { isExistSecondEmail = true; } EmailMessage mail = mailList[0]; mail.Load(); strEmailRic = TWHelper.ClearHtmlTags(mail.Body.ToString()); Regex regex = new Regex(strPattern); MatchCollection matches = regex.Matches(strEmailRic); foreach (Match match in matches) { listRic.Add(match.Groups["RIC"].Value); } if (strEmailKeyWord.Equals("TAIFO IFFM - EDA Automation Report")) { countListRic = listRic.Count; if (listRic.Count == 0) { isExistFirstEmptyEmail = true; } } else { if (listRic.Count == countListRic) { isExistSeconEmptydEmail = true; } } } } catch (Exception ex) { Logger.Log("Get Data from mail failed. Ex: " + ex.Message); } }
static void Main(string[] args) { if (args.Length < 14) { ShowUsage(); Environment.Exit(0); } ExchangeService service = null; if ((args[0] != "-CerValidation")) { ShowUsage(); Environment.Exit(0); } if ((args[1] == "No")) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return(true); }; } Console.WriteLine("[+]CerValidation:{0}", args[1]); if ((args[2] != "-ExchangeVersion")) { ShowUsage(); Environment.Exit(0); } if ((args[3] == "Exchange2007_SP1")) { service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); } else if ((args[3] == "Exchange2010")) { service = new ExchangeService(ExchangeVersion.Exchange2010); } else if ((args[3] == "Exchange2010_SP1")) { service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); } else if ((args[3] == "Exchange2010_SP2")) { service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); } else if ((args[3] == "Exchange2013")) { service = new ExchangeService(ExchangeVersion.Exchange2013); } else if ((args[3] == "Exchange2013_SP1")) { service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); } else { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]ExchangeVersion:{0}", args[3]); if (args[4] == "-u") { UserString = args[5]; Console.WriteLine("[+]User:{0}", args[5]); if ((args[6] != "-p")) { ShowUsage(); Environment.Exit(0); } PwdString = args[7]; Console.WriteLine("[+]Password:{0}", args[7]); service.Credentials = new WebCredentials(UserString, PwdString); } else if (args[4] == "-use") { if (args[5] == "the") { if (args[6] == "default") { if (args[7] == "credentials") { service.UseDefaultCredentials = true; Console.WriteLine("[+]Use the default credentials"); } } } else { ShowUsage(); Environment.Exit(0); } } else { ShowUsage(); Environment.Exit(0); } if ((args[8] == "-ewsPath")) { Console.WriteLine("[+]ewsPath:{0}", args[9]); ewsPathString = args[9]; try { service.Url = new Uri(ewsPathString); } catch (Exception e) { Console.WriteLine("{0}", e.Message); Environment.Exit(0); } } else if ((args[8] == "-AutodiscoverUrl")) { Console.WriteLine("[+]AutodiscoverUrl:{0}", args[9]); AutodiscoverUrlString = args[9]; try { service.AutodiscoverUrl(AutodiscoverUrlString, RedirectionUrlValidationCallback); } catch (Exception e) { Console.WriteLine("{0}", e.Message); Environment.Exit(0); } } else { ShowUsage(); Environment.Exit(0); } if ((args[10] != "-Mode")) { ShowUsage(); Environment.Exit(0); } if ((args[11] == "ListMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } FindItemsResults <Item> findResults = null; FolderString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); if (args[13] == "Inbox") { findResults = service.FindItems(WellKnownFolderName.Inbox, view); } else if (args[13] == "Outbox") { findResults = service.FindItems(WellKnownFolderName.Outbox, view); } else if (args[13] == "DeletedItems") { findResults = service.FindItems(WellKnownFolderName.DeletedItems, view); } else if (args[13] == "Drafts") { findResults = service.FindItems(WellKnownFolderName.Drafts, view); } else if (args[13] == "SentItems") { findResults = service.FindItems(WellKnownFolderName.SentItems, view); } else if (args[13] == "JunkEmail") { findResults = service.FindItems(WellKnownFolderName.JunkEmail, view); } else { ShowUsage(); Environment.Exit(0); } foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); if (item.Subject != null) { Console.WriteLine("[*]Subject:{0}", item.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", item.HasAttachments); if (item.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", item.Id); Console.WriteLine("[*]DateTimeCreated:{0}", item.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", item.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", item.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", item.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", item.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", item.InReplyTo); Console.WriteLine("[*]Size:{0}", item.Size); item.Load(itempropertyset); if (item.Body.ToString().Length > 100) { item.Body = item.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", item.Body); } else { Console.WriteLine("[*]MessageBody:{0}", item.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ListUnreadMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } FindItemsResults <Item> findResults = null; FolderString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); if (args[13] == "Inbox") { findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view); } else if (args[13] == "Outbox") { findResults = service.FindItems(WellKnownFolderName.Outbox, sf, view); } else if (args[13] == "DeletedItems") { findResults = service.FindItems(WellKnownFolderName.DeletedItems, sf, view); } else if (args[13] == "Drafts") { findResults = service.FindItems(WellKnownFolderName.Drafts, sf, view); } else if (args[13] == "SentItems") { findResults = service.FindItems(WellKnownFolderName.SentItems, sf, view); } else if (args[13] == "JunkEmail") { findResults = service.FindItems(WellKnownFolderName.JunkEmail, sf, view); } else { ShowUsage(); Environment.Exit(0); } foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); EmailMessage email = EmailMessage.Bind(service, item.Id); if (email.Subject != null) { Console.WriteLine("[*]Subject:{0}", email.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", email.HasAttachments); if (email.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, email.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", email.Id); Console.WriteLine("[*]DateTimeCreated:{0}", email.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", email.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", email.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", email.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", email.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", email.InReplyTo); Console.WriteLine("[*]Size:{0}", item.Size); email.Load(itempropertyset); if (email.Body.ToString().Length > 100) { email.Body = email.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", email.Body); } else { Console.WriteLine("[*]MessageBody:{0}", email.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } if ((args[11] == "ListFolder")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } FolderString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); FindFoldersResults findResults = null; FolderView view = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep }; if (args[13] == "Inbox") { findResults = service.FindFolders(WellKnownFolderName.Inbox, view); } else if (args[13] == "Outbox") { findResults = service.FindFolders(WellKnownFolderName.Outbox, view); } else if (args[13] == "DeletedItems") { findResults = service.FindFolders(WellKnownFolderName.DeletedItems, view); } else if (args[13] == "Drafts") { findResults = service.FindFolders(WellKnownFolderName.Drafts, view); } else if (args[13] == "SentItems") { findResults = service.FindFolders(WellKnownFolderName.SentItems, view); } else if (args[13] == "JunkEmail") { findResults = service.FindFolders(WellKnownFolderName.JunkEmail, view); } else { ShowUsage(); Environment.Exit(0); } foreach (Folder folder in findResults.Folders) { Console.WriteLine("\r\n"); Console.WriteLine("[*]DisplayName:{0}", folder.DisplayName); Console.WriteLine("[*]Id:{0}", folder.Id); Console.WriteLine("[*]TotalCount:{0}", folder.TotalCount); } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ListMailofFolder")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); Folder Folders = Folder.Bind(service, IdString); FindItemsResults <Item> findResults = null; ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; findResults = Folders.FindItems(view); foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); if (item.Subject != null) { Console.WriteLine("[*]Subject:{0}", item.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", item.HasAttachments); if (item.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", item.Id); Console.WriteLine("[*]DateTimeCreated:{0}", item.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", item.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", item.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", item.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", item.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", item.InReplyTo); Console.WriteLine("[*]Size:{0}", item.Size); item.Load(itempropertyset); if (item.Body.ToString().Length > 100) { item.Body = item.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", item.Body); } else { Console.WriteLine("[*]MessageBody:{0}", item.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ListUnreadMailofFolder")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); Folder Folders = Folder.Bind(service, IdString); FindItemsResults <Item> findResults = null; ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; findResults = Folders.FindItems(sf, view); foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); EmailMessage email = EmailMessage.Bind(service, item.Id); if (email.Subject != null) { Console.WriteLine("[*]Subject:{0}", email.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", email.HasAttachments); if (email.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, email.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", email.Id); Console.WriteLine("[*]DateTimeCreated:{0}", email.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", email.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", email.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", email.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", email.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", email.InReplyTo); Console.WriteLine("[*]Size:{0}", email.Size); email.Load(itempropertyset); if (email.Body.ToString().Length > 100) { email.Body = email.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", email.Body); } else { Console.WriteLine("[*]MessageBody:{0}", email.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "SaveAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; Console.WriteLine("[+]Attachments:{0}", fileAttachment.Name); fileAttachment.Load(fileAttachment.Name); Console.WriteLine("\r\n[+]SaveAttachment success"); } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "AddAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); if ((args[14] != "-AttachmentFile")) { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]AttachmentFile:{0}", args[15]); EmailMessage message = EmailMessage.Bind(service, IdString); message.Attachments.AddFileAttachment(args[15]); message.Update(ConflictResolutionMode.AlwaysOverwrite); Console.WriteLine("\r\n[+]AddAttachment success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ClearAllAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments)); message.Attachments.Clear(); message.Update(ConflictResolutionMode.AlwaysOverwrite); Console.WriteLine("\r\n[+]ClearAllAttachment success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "DeleteAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); if ((args[14] != "-AttachmentFile")) { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]AttachmentFile:{0}", args[15]); EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { if (attachment.Name == args[15]) { message.Attachments.Remove(attachment); break; } } message.Update(ConflictResolutionMode.AlwaysOverwrite); Console.WriteLine("\r\n[+]DeleteAttachment success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "DeleteMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); EmailMessage message = EmailMessage.Bind(service, IdString); message.Delete(DeleteMode.SoftDelete); Console.WriteLine("\r\n[+]DeleteMail success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "SearchMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-String")) { ShowUsage(); Environment.Exit(0); } SearchString = args[13]; Console.WriteLine("[+]SearchString:{0}", args[13]); SearchMail(service, WellKnownFolderName.Inbox, SearchString); SearchMail(service, WellKnownFolderName.Outbox, SearchString); SearchMail(service, WellKnownFolderName.DeletedItems, SearchString); SearchMail(service, WellKnownFolderName.Drafts, SearchString); SearchMail(service, WellKnownFolderName.SentItems, SearchString); SearchMail(service, WellKnownFolderName.JunkEmail, SearchString); Console.WriteLine("\r\n[+]SearchMail done"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ExportMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); Console.WriteLine("[+]SavePath:{0}.eml", args[13]); Folder inbox = null; if (args[13] == "Inbox") { inbox = Folder.Bind(service, WellKnownFolderName.Inbox); } else if (args[13] == "Outbox") { inbox = Folder.Bind(service, WellKnownFolderName.Outbox); } else if (args[13] == "DeletedItems") { inbox = Folder.Bind(service, WellKnownFolderName.DeletedItems); } else if (args[13] == "Drafts") { inbox = Folder.Bind(service, WellKnownFolderName.Drafts); } else if (args[13] == "SentItems") { inbox = Folder.Bind(service, WellKnownFolderName.SentItems); } else if (args[13] == "JunkEmail") { inbox = Folder.Bind(service, WellKnownFolderName.JunkEmail); } else { Console.WriteLine("[!]Don't support this folder"); Environment.Exit(0); } ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); FindItemsResults <Item> results = inbox.FindItems(view); int i = 0; foreach (var item in results) { i++; PropertySet props = new PropertySet(EmailMessageSchema.MimeContent); var email = EmailMessage.Bind(service, item.Id, props); string emlFileName = args[13] + ".eml"; using (FileStream fs = new FileStream(emlFileName, FileMode.Append, FileAccess.Write)) { fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length); } } Console.WriteLine("\r\n[+]ExportMail done,total number:{0}", i); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ViewMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); ViewMail(service, WellKnownFolderName.Inbox, IdString); ViewMail(service, WellKnownFolderName.Outbox, IdString); ViewMail(service, WellKnownFolderName.DeletedItems, IdString); ViewMail(service, WellKnownFolderName.Drafts, IdString); ViewMail(service, WellKnownFolderName.SentItems, IdString); ViewMail(service, WellKnownFolderName.JunkEmail, IdString); Console.WriteLine("\r\n[+]ViewMail done"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ReadXML")) { Console.WriteLine("[+]Mode:{0}", args[11]); if ((args[12] != "-Path")) { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]XML path:{0}", args[13]); Console.WriteLine("[+]Out path:out.xml"); StreamReader sendData = new StreamReader(args[13], Encoding.Default); byte[] sendDataByte = Encoding.UTF8.GetBytes(sendData.ReadToEnd()); sendData.Close(); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(service.Url); request.Method = "POST"; request.ContentType = "text/xml"; request.ContentLength = sendDataByte.Length; request.AllowAutoRedirect = false; if (args[4] == "-use") { request.Credentials = CredentialCache.DefaultCredentials; } else { request.Credentials = new NetworkCredential(UserString, PwdString); } Stream requestStream = request.GetRequestStream(); requestStream.Write(sendDataByte, 0, sendDataByte.Length); requestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { throw new WebException(response.StatusDescription); } Stream receiveStream = response.GetResponseStream(); StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); String receiveString = readStream.ReadToEnd(); response.Close(); readStream.Close(); StreamWriter receiveData = new StreamWriter("out.xml"); receiveData.Write(receiveString); receiveData.Close(); } catch (WebException e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } Console.WriteLine("\r\n[+]ReadXML done"); } }