private static void ExpandDistributionLists(ExchangeService service) { // Retrieve the expanded group from the server. // Note that an invalid group will throw an exception which should be handled. ExpandGroupResults groupMembers = null; try { // Note: Replace "*****@*****.**" with the distribution list you wish to expand. groupMembers = service.ExpandGroup("*****@*****.**"); } catch (ServiceResponseException SREx) { if (SREx.ErrorCode == ServiceError.ErrorNameResolutionNoResults) { Console.WriteLine("The email address does not contain a valid group: {0}", SREx.ErrorCode); return; } else { throw (SREx); } } finally { if (groupMembers != null) { // Display the group members to the console. foreach (EmailAddress address in groupMembers.Members) { Console.WriteLine("Email Address: {0}", address.Address); } } } }
/// <summary> /// We will export the members of the group. /// </summary> private static void ExportGroup(ExchangeService service, String groupAddress, String pad, Boolean isRecursive, StreamWriter writer) { ExpandGroupResults groupMembers = service.ExpandGroup(groupAddress); if (String.IsNullOrEmpty(pad)) { pad = ""; } // Add spaces for view pad += " "; foreach (EmailAddress member in groupMembers) { // If we need recursion, and the member is group, we will process the method recursively. if (isRecursive & (member.MailboxType == MailboxType.ContactGroup || member.MailboxType == MailboxType.PublicGroup)) { Console.WriteLine(pad + "{0,-50}{1,-11}", member.Address, member.MailboxType); ExportGroup(service, member, pad, isRecursive, writer); } else { Console.WriteLine(pad + "{0,-50}{1,-11}", member.Address, member.MailboxType); writer.WriteLine("\"{0}\",\"{1}\"", groupAddress, member.Address); } } }
private void ExpandDL_PublicGroup(ref TreeNode oParentNode, ItemId groupID) { this.Cursor = System.Windows.Forms.Cursors.WaitCursor; try { // Return the expanded group. ExpandGroupResults myGroupMembers = _CurrentService.ExpandGroup(groupID); // Display the group members. foreach (EmailAddress address in myGroupMembers) { if (address.MailboxType == MailboxType.PublicGroup || address.MailboxType == MailboxType.ContactGroup) { //oParentNode = AddNode(ref oParentNode, address); //oParentNode.Nodes.Add(""); // Add dummy ExpandDL_PublicGroup(ref oParentNode, address.Address); } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } this.Cursor = System.Windows.Forms.Cursors.Default; }
private static void PrintContactGroupHelper(Item item) { ContactGroup contactGroup = item as ContactGroup; // This results in a GetItem operation call to EWS. This loads all the properties, // including the members of the ContactGroup. contactGroup.Load(); Console.WriteLine("Contact group name ({0} members): " + contactGroup.DisplayName, contactGroup.Members.Count.ToString()); if (contactGroup.Members.Count > 0) { ExpandGroupResults expandResults = service.ExpandGroup(contactGroup.Id); foreach (EmailAddress address in expandResults.Members) { try { Item expandedItem = Item.Bind(service, address.Id); ContactOrContactGroupHelper(expandedItem); } catch (ServiceResponseException ex) { Console.WriteLine("Found a reference to contact item that does not exist in your mailbox. You might want to delete this entry from your contact group."); } } } }
private void ExpandDL_PublicGroup(ref TreeNode oParentNode, string sSmtp) { TreeNode oNode = null; try { // Return the expanded group. ExpandGroupResults myGroupMembers = _CurrentService.ExpandGroup(sSmtp); // Display the group members. foreach (EmailAddress address in myGroupMembers) { if (address.MailboxType == MailboxType.PublicGroup || address.MailboxType == MailboxType.ContactGroup) { oNode = AddNode(ref oParentNode, address); //address.MailboxType = MailboxType.ContactGroup //address.RoutingType = string oNode.Nodes.Add(""); // Add dummy } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
private void button1_Click(object sender, EventArgs e) { NameResolutionCollection nameResolutions = service.ResolveName( "<group_name>", ResolveNameSearchLocation.DirectoryOnly, true); foreach (NameResolution nameResolution in nameResolutions) { ExpandGroupResults groupResults = service.ExpandGroup(nameResolution.Mailbox.Address); foreach (EmailAddress member in groupResults.Members) { Console.WriteLine(member.Name + " <" + member.Address + ">"); } } }
/// <summary> /// Expands the distribution lists. /// </summary> /// <param name="target">The target.</param> /// <returns>IReadOnlyList</returns> public IReadOnlyList <string> ExpandDistributionLists(string target) { try { // Return the expanded group. this.DistributionList = target; ExpandGroupResults myGroupMembers = this.Exchange.ExpandGroup(this.DistributionList); var emailCollection = (from x in myGroupMembers.Members select x.Address); return(emailCollection.ToList()); } catch (Exception ex) { throw ex; } }
private void DispalyNonDls(TreeNode oParentNode) { lvItems.Items.Clear(); EmailAddress oEmailAddress = (EmailAddress)oParentNode.Tag; if (oEmailAddress != null) { string sSmtp = oEmailAddress.Address; ListViewItem oItem = null; try { // Return the expanded group. ExpandGroupResults myGroupMembers = _CurrentService.ExpandGroup(oEmailAddress); // Display the group members. foreach (EmailAddress address in myGroupMembers.Members) { if (address.MailboxType != MailboxType.PublicGroup && address.MailboxType != MailboxType.PublicGroup) { oItem = lvItems.Items.Add(address.Name); oItem.SubItems.Add(address.Address); oItem.SubItems.Add(address.MailboxType.ToString()); oItem.SubItems.Add(address.RoutingType); if (address.Id != null) { oItem.SubItems.Add(address.Id.UniqueId); } else { oItem.SubItems.Add(""); } oItem.Tag = address; } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } }
/// <summary> /// /// </summary> /// <returns>Integer 1: Success, -1 = Fail</returns> public int Send() { // Connect to exchange_service exchange_service = new ExchangeService(ExchangeVersion.Exchange2010); exchange_service.Url = new Uri(exchange_uri); exchange_service.UseDefaultCredentials = true; // Create the email EmailMessage emailMessage = new EmailMessage(exchange_service); // Subject emailMessage.Subject = this.subject; //Body if (use_html) { emailMessage.Body = new MessageBody(BodyType.HTML, this.html_body); } else { emailMessage.Body = new MessageBody(BodyType.HTML, this.body); } // Add Recipients foreach (string rep in this.recipients) { emailMessage.ToRecipients.Add(rep); } // Add Distribution List Persons foreach (string dist in this.distribution_groups) { ExpandGroupResults grp = exchange_service.ExpandGroup(dist); foreach (EmailAddress em in grp.Members) { emailMessage.ToRecipients.Add(em.Address); } } //Add Attachements foreach (string att in this.attachments) { emailMessage.Attachments.AddFileAttachment(att); } // Add Inline attachments //https://msdn.microsoft.com/en-us/library/office/hh532564(v=exchg.80).aspx foreach (Tuple <string, string> tup in this.inline_attachments) { string contentID = tup.Item1; string file = tup.Item2; FileAttachment fileAttachment = emailMessage.Attachments.AddFileAttachment(file); fileAttachment.ContentId = contentID; fileAttachment.IsInline = true; } // Save and send try { emailMessage.Save(); emailMessage.SendAndSaveCopy(); } catch { return(-1); } return(0); }
ExchangeResult ExecuteOperation(EmailOperation operation, string address, Dictionary <string, bool> processed = null) { // create processed addresses dictionary if it does not exist if (processed == null) { processed = new Dictionary <string, bool>(); } // dont reprocess this address if we have already processed it if (processed.ContainsKey(address)) { return(null); } // try to find a mailbox for the address on one of the tenants ExchangeService service = null; EmailAddress mailbox = null; foreach (WebCredentials cred in credentials) { service = new ExchangeService(); service.Credentials = cred; service.Url = new Uri(ConfigurationManager.AppSettings["url"]); try { NameResolutionCollection results = service.ResolveName("smtp:" + address); if (results.Count > 0) { mailbox = results[0].Mailbox; break; } } catch (Exception e) { return(new ExchangeResult(address, StatusCode.Error, "Failed to resolve name: " + e.Message)); } } // if we did not find a mailbox for the address on any of the tenants then report recipient not found if (mailbox == null) { return(new ExchangeResult(address, StatusCode.RecipientNotFound, "recipient not found")); } // add resolved address to processed list to prevent reprocessing processed.Add(mailbox.Address, true); // if this mailbox is a group/distribution list if (mailbox.MailboxType == MailboxType.PublicGroup) { // attempt to expand the group ExpandGroupResults group = null; try { group = service.ExpandGroup(mailbox.Address); } catch (Exception e) { // report failure to expand group if an exception occurs during expansion return(new ExchangeResult(mailbox.Address, StatusCode.Error, "Failed to expand group: " + e.Message)); } // for every member in the group ExchangeResult result = new ExchangeResult(); foreach (EmailAddress member in group.Members) { // recursively execute operation and log results result.Log(ExecuteOperation(operation, member.Address, processed)); } // return the results return(result); } // if this is just a regular mailbox else if (mailbox.MailboxType == MailboxType.Mailbox) { // set impersonation to the mailbox address service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailbox.Address); // attempt to get some info to see if impersonation worked try { DateTime?dt = service.GetPasswordExpirationDate(mailbox.Address); } catch (Exception e) { // if we were unable to impersonate the user then report error return(new ExchangeResult(mailbox.Address, StatusCode.Error, "impersonation failed: " + e.Message)); } // delete email if operation is delete if (operation == EmailOperation.Delete) { try { // find all instances of the email with message_id in the mailbox FolderView folderView = new FolderView(int.MaxValue); folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName); folderView.Traversal = FolderTraversal.Shallow; SearchFilter folderFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "AllItems"); FindFoldersResults folders = service.FindFolders(WellKnownFolderName.Root, folderFilter, folderView); SearchFilter filter = new SearchFilter.IsEqualTo(EmailMessageSchema.InternetMessageId, message_id); ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.Traversal = ItemTraversal.Shallow; List <ItemId> items = new List <ItemId>(); foreach (Item item in service.FindItems(folders.Folders[0].Id, filter, view)) { items.Add(item.Id); } // if no instances of the email were found in the mailbox then report message_id not found if (items.Count == 0) { return(new ExchangeResult(mailbox.Address, StatusCode.MessageNotFound, "message_id not found")); } // delete all found instances of the email with message_id from the mailbox foreach (ServiceResponse response in service.DeleteItems(items, DeleteMode.SoftDelete, null, null)) { // if we failed to delete an instance of the email then report an error if (response.Result != ServiceResult.Success) { string message = "failed to delete email: " + response.ErrorCode + " " + response.ErrorMessage; return(new ExchangeResult(mailbox.Address, StatusCode.Error, message)); } } } catch (Exception e) { //report any errors we encounter return(new ExchangeResult(mailbox.Address, StatusCode.Error, "failed to delete email: " + e.Message)); } } // recover email if operation is recover else if (operation == EmailOperation.Restore) { try { // find all instances of the email with message_id in the recoverable items folder SearchFilter filter = new SearchFilter.IsEqualTo(EmailMessageSchema.InternetMessageId, message_id); ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.Traversal = ItemTraversal.Shallow; List <ItemId> items = new List <ItemId>(); foreach (Item item in service.FindItems(WellKnownFolderName.RecoverableItemsDeletions, filter, view)) { items.Add(item.Id); } // if no instances of the email with message_id were found in the recoverable items folder of the mailbox if (items.Count == 0) { // report message_id not found return(new ExchangeResult(mailbox.Address, StatusCode.MessageNotFound, "message_id not found")); } // move every instance of the email with message_id in the recoverable items folder to the inbox foreach (ServiceResponse response in service.MoveItems(items, new FolderId(WellKnownFolderName.Inbox))) { // if we failed to move an instance of the email to the inbox then report an error if (response.Result != ServiceResult.Success) { string message = "failed to recover email: " + response.ErrorCode + " " + response.ErrorMessage; return(new ExchangeResult(mailbox.Address, StatusCode.Error, message)); } } } catch (Exception e) { // report any errors we encounter return(new ExchangeResult(mailbox.Address, StatusCode.Error, "failed to recover email: " + e.Message)); } } // report successful operation return(new ExchangeResult(mailbox.Address, StatusCode.Success, "success")); } // report that the mailbox type is not one of the supported types return(new ExchangeResult(mailbox.Address, StatusCode.Error, "Unsupported mailbox type: " + mailbox.MailboxType.ToString())); }
private void DispalyNonDls(TreeNode oParentNode) { this.Cursor = System.Windows.Forms.Cursors.WaitCursor; lvItems.Items.Clear(); if (oParentNode.Tag != null) { // typeof oto = oParentNode.Tag.GetType(); if (oParentNode.Tag.GetType() != typeof(ItemId)) //(oParentNode.Tag.GetType() == typeof(string)) { EmailAddress oEmailAddress = (EmailAddress)oParentNode.Tag; string sSmtp = oEmailAddress.Address; ListViewItem oItem = null; try { // Return the expanded group. ExpandGroupResults myGroupMembers = _CurrentService.ExpandGroup(oEmailAddress); // Display the group members. foreach (EmailAddress address in myGroupMembers.Members) { if (address.MailboxType != MailboxType.PublicGroup && address.MailboxType != MailboxType.PublicGroup) { oItem = lvItems.Items.Add(address.Name); oItem.SubItems.Add(address.Address); oItem.SubItems.Add(address.MailboxType.ToString()); oItem.SubItems.Add(address.RoutingType); if (address.Id != null) { oItem.SubItems.Add(address.Id.UniqueId); } else { oItem.SubItems.Add(""); } oItem.Tag = address; } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } else if (oParentNode.Tag.GetType() == typeof(ItemId)) { string s = (oParentNode.Tag.ToString()); ItemId oItemId = new ItemId(oParentNode.Tag.ToString()); ListViewItem oItem = null; try { // Return the expanded group. ExpandGroupResults myGroupMembers = _CurrentService.ExpandGroup(oItemId); // Display the group members. foreach (EmailAddress address in myGroupMembers.Members) { if (address.MailboxType != MailboxType.PublicGroup && address.MailboxType != MailboxType.PublicGroup) { oItem = lvItems.Items.Add(address.Name); oItem.SubItems.Add(address.Address); oItem.SubItems.Add(address.MailboxType.ToString()); oItem.SubItems.Add(address.RoutingType); if (address.Id != null) { oItem.SubItems.Add(address.Id.UniqueId); } else { oItem.SubItems.Add(""); } oItem.Tag = address; } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } this.Cursor = System.Windows.Forms.Cursors.Default; }