Retrieval of all users in Exchange online

Exchange Version: Exchange Online at Office 365
API Name: EWS API 2.0
IDE: Visual basic C# 2010
Targeted features: Impersonation and retrieval of all users
Hi there, I am currently developing a program that uses impersonation and queries the EWS API to retrieve emails and their attachments from users. I have used the C# codes from the MSDN Library to develop the program. The program is successful in retrieving
the emails from specific users that are hard coded into the program.
The code below shows the process of authenticating the admin user and the impersonation is done in the  RetrieveEmailFromUser() function.
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new NetworkCredential("adminemail@", "password", "domain.onmicrosoft.com");
service.AutodiscoverUrl("adminemail", RedirectionUrlValidationCallback);
List<string> emailaddrlist = new List<string>();
emailaddrlist.Add("[email protected]");
emailaddrlist.Add("[email protected]");
foreach (string item in emailaddrlist)
string content = RetrieveEmailFromUser(service, item);
Console.WriteLine(content);
        static string RetrieveEmailFromUser(ExchangeService service, string emailAddr)
            service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddr);
            FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(50));
As can be seen from the coding, the users that are to be impersonated have been hardcoded. I would like to know if there are any C# codes or a link to a page where it describes how I can retrieve ALL users with mailboxes from a Microsoft 365 admin account
without needing to manually add users for retrieval.

Hi there sorry for asking again but I have successfully retrieved all the users but now I would need to filter them to lower the amount of addresses retrieved.
For example
owershell.Runspace = runspace;
//Create the command and add the parameters to retrieve all users that have mailboxes
powershell.AddCommand("Get-Mailbox");
powershell.AddParameter("RecipientTypeDetails", "UserMailbox");
//Invoke the command and store the results in a PSObject collection
Collection<PSObject> EmailList = powershell.Invoke();
//Iterate through the results and add the PrimarySMTP address for each mailbox to emailAddrlist
foreach (PSObject emailAddr in EmailList)
string time = emailAddr.Properties["WhenCreated"].Value.ToString();
string addr = emailAddr.Properties["PrimarySmtpAddress"].Value.ToString();
EmailAddrList.Add(addr + time);
The property ("WhenChanged") will retrieve the date time when the mailbox had its options MODIFIED but not when an email is received. Is there a parameter I can input using powershell to retrieve users who have new emails in their mailboxes from
a specific? Or can I change the value of the Property from  ("WhenChanged") to something else that will give me a date time of the most recent addition of an email to the mailbox. This will then allow me to compare the date time to filter out
addresses which have not received any emails.
Thank you.

Similar Messages

  • How to access unread mails of all users in Exchange server without having Passwords and without giving mailbox access to other user.

    Hi all,
       I am using Exchange server 2013, my task is to create
    Service , that
    need's to  monitor continuously for new mails of all Mailboxes in
    my server. if any user got new mail i need to get that Mail Subject, Mail Body, Sender Email Address [From emailId] .  
    Limitation
    : I don't have Passwords of mailboxes , so i gave all mailbox access permission  to one user , then i completed this   service using below code.
     But now, Client
    not willing to give Mailbox Permissions to one user because of security problems.
    How can i do this without passwords and without giving permissions to other user ?
    i don't want all mailbox access , i just need only
    access Mail Subject , Body and Sender mail address .
    How can i achieve
    this ?
    Process i follow
    => I created new user in server , and then i gave full permissions of all Mailboxes to newly created user[ex: james] in database level.
         i use below command for giving permissions in database level.
    Get-MailboxDatabase -Identity <Database Name> | Add-ADPermission -User <User> -AccessRights GenericAll
     => using below code i am searching unread mails of all user Mailboxes and then getting Subject, body and Sender Email            address . here i am have list of users,
    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
    service.Credentials = new WebCredentials("[email protected]", "password");
    service.AutodiscoverUrl("[email protected]");  foreach (Object obj in usersList) // here i have Mailbox users list in usersList
                 { var userMailbox = new Mailbox(obj.user);
    var folderId = new FolderId(WellKnownFolderName.Inbox, userMailbox);
    SearchFilter.IsEqualTo filter1 = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
    var itemView = new ItemView(50);
    var userItems = service.FindItems(folderId, filter1, itemView);
    foreach (var item in userItems)
    item.Load();
    var senderEmail = ((EmailMessage)item).From;
    var subject = item.Subject;
    var body = item.Body;

    You would need to check that possibilities via WebServices but suggest you to post this in Development forum to get help from programmers....
    http://social.technet.microsoft.com/Forums/office/en-US/home?forum=exchangesvrdevelopment
    Blog |
    Get Your Exchange Powershell Tip of the Day from here

  • How to retrieve the all user name from system domain(including login user)?

    Hi, I am trying to get the system domain all users name. But I unable to get the all user name except domain login user name. I used the below code. What I want to do to get the all user name from system domain. Kindly any one help me.
    Properties envVars = new Properties();
    Runtime r = Runtime.getRuntime();
    String OS = System.getProperty("os.name").toLowerCase();
         if ((OS.indexOf("nt") > -1) || (OS.indexOf("windows 2000") > -1 ) || (OS.indexOf("windows xp") > -1) )
              p = r.exec( "cmd.exe /c set" );
         BufferedReader br = new BufferedReader ( new InputStreamReader( p.getInputStream() ) );
         String line;
         while( (line = br.readLine()) != null )
              int idx = line.indexOf( '=' );
              String key = line.substring( 0, idx );
              String value = line.substring( idx+1 );
              envVars.setProperty( key, value );
         String domainDNSName = envVars.getProperty("USERDNSDOMAIN");
         String userName = envVars.getProperty("USERNAME");
         System.out.println("\n\n\n DOMAIN NAME == "+domainDNSName +" USERNAME == "+userName);
    Thanks & Regards
    Palani

    Thanks kajbj,
    I don't know, How many users in domain. I neet to get all the user names from my domain. User like A, B,C,D, E,F. I need to get this users name.
    public class Env {
         public static void main(String[] args) {
              System.out.println("USERDOMAIN: " + System.getenv("USERDOMAIN"));
              System.out.println("USERNAME: " + System.getenv("USERNAME"));
    Here , I am getting the login user name only. So i needs all user name. How to retrive or get this.
    Regards
    Palani

  • Delete Single Email from sender to All Users in Exchange 2010

    Dear All,
    I have received one virus from 163.com. i want to delete all mails coming from 163.com to all users mailbox. the subject and attachment words are common so we can not delete it by attachment name or subject name.
    pls help me to delete by domain.
    Sunil
    SUNIL PATEL SYSTEM ADMINISTRATOR

    Before I do a search and remove like this, I like to run a message track first, to see how widespread the issue is. If it's only a few users who received the message, I would just run search-mailbox against their identity and remove the email. Here's an
    example of the message track I would run:
    Get-TransportServer | Invoke-Command {Get-MessageTrackingLog -Sender "[email protected]" -MessageSubject "Important information about your account" -Start "09/08/2014 00:01:00 AM" -End "09/11/2014 10:00:00 AM" | Select
    Sender,{$_.Recipients},{$_.RecipientStatus},MessageSubject,TimeStamp, EventId, Source, SourceContext,MessageId,InternalMessageId,ClientIP,ClientHostName,ServerIP,ServerHostName,ConnectorId,TotalBytes,RecipientCount,RelatedRecipientAddress,Reference,ReturnPath,MessageInfo
    | Export-Csv E:\temp\MessageTrackingLog-ShadyBiz.csv -NoTypeInformation}
    Then, if it's a few users, I get their identity info from the spreadsheet and run this on each:
    Search-Mailbox -Identity michaeld -SearchQuery subject:"Important information about your account", Sent:'09/08/2014..09/11/2014', from:'[email protected]' -TargetMailbox "ex2010security"
    -TargetFolder "ShadyBiz" -Loglevel Full -DeleteContent -Force -Confirm:$false
    This would put the found messages into a folder called ShadyBiz in a mailbox I designate, then delete the content from the user's mailbox (you could then use the info in the folder for reporting purposes
    and delete it once you are done).
    If you find you have to run this against all the mailboxes in your company, you might want to try this approach:
    $mbs=Get-Mailbox –ResultSize Unlimited | Where {($_.PrimarySMTPAddress –like ‘*yourcompany.com*’) –and ($_.RecipientTypeDetails –eq ‘UserMailbox’)}
    ForEach ($mb in $mbs) {Search-Mailbox -Identity $mb.identity -SearchQuery subject:"Important information about your account", Sent:'09/08/2014..09/11/2014', from:'[email protected]' -TargetMailbox
    "ex2010security" -TargetFolder "ShadyBiz" -Loglevel Full -DeleteContent -Force -Confirm:$false}

  • Bulk User creation Exchange Online Protection standalone

    Hi,
    We have on premise Exchange 2013 servers and we're planned to go for EOP only for SPAM filtering. I have couple of questions with EOP:
    When we create bulk user accounts from a CSV file do we need to Allow users to sign in to EOP?
    what will be the EOP address for On-Premise send connector(send emails from the organization)? and how to get it?
    is there any proper step by step guide to setup EOP standalone?
    Thanks..
    Roshan

    You don't need to allow sign in today, but in the
    future there will be a personal
    quarantine for users.
    set the value to the MX record given to you during EOP setup, such as <your organization>-com.mail.protection.outlook.com.
    (http://community.office365.com/en-us/wikis/exchange/4238.aspx)
    http://technet.microsoft.com/en-us/library/jj723153(v=exchg.150).aspx
    Mike Crowley | MVP
    My Blog --
    Planet Technologies

  • Exchange Online without configuration outlook.

    Hello.
    I’ve tested Exchange Online Plan1 by trial version now.
    I saw your article of the migration Exchange Server 2003 to Office365.
    My goal is using exchange online without setting on user computers.
    Because many user are in different place. So I couldn’t make it all of them.
    And it could be taken time a lot. That’s why I don’t want configuration of the outlook.
    But I’m not sure it is possible. Please let me know my big question.
    My Exchange Online Migration Plan.
    Stop our Exchange Server 2003.
    Make contract with Microsoft for Exchange Online Plan1
    Register our domain on the Exchange Online.
    Make all of the users at Exchange Online without migration function.
    Reconfiguration  passwords of the users by powershell.
    Using outlook 2007 without reconfiguration.
     If I use Exchange Server 2013, it is possible to use outlook 2007 without configuration
    Thank you.

    Hi,
    Since the issue is related to Exchange Online, I recommend you ask for more professional help on our Exchange Online forum:
    http://social.technet.microsoft.com/Forums/msonline/en-US/home?forum=onlineservicesexchange
    Best regards,
    Angela
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • Sideloading metro apps for all users

    I am having problems with my sideloaded metro app…… Doesn’t seem to work anymore on any of my machines.
    For the first few months, I originally installed my Metro app by first installing the app’s signed certificate to the local machine root store (All OK), then running the following command logged on as the actual user I wanted the app run
    under.
    Add-AppxPackage
    -Path "MyMetroApp.appx"
    -ForceApplicationShutdown
    While this method sort of worked, it had two problems:
    I needed to manually renew the developer licence every 30 days running
    Show-WindowsDeveloperLicenseRegistration
    and I had to do this logged on as the user on the actual console, couldn’t to this using remote PowerShell.
    I want to install the app properly for all users without needing to keep renewing the developer license. I have now run the following to install the app for all users:
    #Allow Trusted Apps
    New-Item
    -Path "HKLM:\Software\Policies\Microsoft\Windows\Appx"
    New-ItemProperty
    -Path "HKLM:\Software\Policies\Microsoft\Windows\Appx"
    -Name AllowAllTrustedApps
    -PropertyType DWord
    -Value 1
    #Install the app for all users
    Add-ProvisionedAppxPackage
    -Online -PackagePath
    "MyMetroApp.appx"
    -SkipLicense
    This method – even though it seemed to complete successfully, a couple of issues:
    there’s no shortcut added to the start screen on one of my machines, so I can’t open the app
    I am getting a message popup upon opening my app “The app can’t open: There's a problem with {app name}. Contact your system administrator about repairing or reinstalling it. [Close].” on another machine
    Can someone please point me in right direction to get my app working again? I don’t think it’s anything major, I think I’m on the right track.

    The main steps are detailed here:
    https://technet.microsoft.com/en-us/library/hh852635.aspx
    It sounds like the app needs to be un-provisioned on your troublesome machine ?
    Don
    (Please take a moment to "Vote as Helpful" and/or "Mark as Answer", where applicable.
    This helps the community, keeps the forums tidy, and recognises useful contributions. Thanks!)

  • Access all users folders on MS Exchange Server

    Using the javax.mail class, I can establish a Session, connect to a Store and retrieve all messages from INBOX folder. With this approach I must know the username/password to do the connect.
    What I really want to do is to access the INBOX folder for all users without knowing the username/password. Is there a way to do this? Can I configure the MS Exchange Server to include a special user and use that username/password to access all other user�s mailboxes? Any suggestion would be helpful.

    Let me just paraphrase what you just wrote.
    "MS Exchange has security that prevents me from reading other people's e-mail unless I know their passwords. How can I break this security?"
    Apart from whether this is legal or ethical at all, what sort of security would it be if you could just do something simple to avoid it?

  • Decommission Exchange 2010 after all mailboxes have been moved to Exchange Online

    Currently very confused on what to do.
    I'm looking to migrate mailboxes to Exchange online using a Hybrid deployment with Dirsync. The users have multiple email and domain addresses. They are moving away from their SBS 2011 and Exch 2010 server. They have an AD and File and Print server. Once
    all mailboxes are moved and mx records are changed and everything is running smootkly. I would like to then decommission SBS and Exch 2010 box and still use DIRsync
    Few questions
    Once I remove Exch 2010 what wont I be able to do. Cant find anything specific online
    Will I still be able to create a user in AD then login to Exchange online and assign a license then
    the user would have mailbox
    Edit a user and add smtp email address.
    As I don’t have many users should I rather use PST migration or will I run into the same problems.

    Yes, you should move the arbitration mailboxes - they are organizational mailboxes, not mailbox database mailboxes.
    Make sure all Exchange resources and operations hosted on this server have been moved to your Exchange 2013 system before you remove Exchange from this server.  If you try to remove Exchange (in either the GUI or the command line) and something is
    still using this server, you will be alerted that something is still using the server and will be told what it is.
    HTH ...

  • Error migrating user from on-premises Exchange to Exchange online

    We have a hybrid configuration with our on-premises Exchange 2010 server and our Office 365 Exchange Online server (if this should be posted in the Exchange 2010 forum instead, let me know, but I figured we have one of each).  We have been doing remote
    moves, and all but two of them are finished. The two remaining are refusing to go, and I've done extensive searching but haven't been able to resolve the issues.
    The first mailbox returns this error message:
    Error: MissingExchangeGuidException: The user object for ‎nnn
    does not have a valid ExchangeGuid property and cannot be migrated.
    The second mailbox returns this error message:
    Error: MigrationTransientException: Couldn‎'t find a move request that corresponds to the specified identity
    <‎identity>.
    We've tried moving both mailboxes several times (deleting the migration batch after each error) with no luck.   The migration for both of these users are being done as separate batches with one user in each batch.  They are being created via the
    Exchange Admin Center from the Office 365 admin portal.  Any suggestions on what to do next?

    Hi Dave,
    I have gone thorough your query, its ok. Pplease follow this informative article that provides the steps Mailbox Migration to Exchange Online : https://technet.microsoft.com/en-us/library/jj863291%28v=exchg.150%29.aspx
    In addition if you want to move mailboxes automatically you may also have a look on
    Lepide Exchange Recovery Manager that could be a good alternative solution for you.
    It is complete disaster recovery, backup restoration, and Exchange to Exchange or Exchange to Office 365 migration tool and one stop solution.

  • Is it possible to switch from Office 365 online user management to Active Directory after Exchange online migration?

    If we utilize the Cutover method to migrate from on-premise Exchange (2007) to Office 365, which to my understanding will hand over user management/authentication to Office 365 online during the process, is possible to later switch from Office 365 user management
    to Active Directory (synced to a future local domain, or even possibly via AD federation single sign-on)? If so, how difficult is this process and is there any documentation available?
    Asking this because the organization  I'm working for plans to upgrade (re-do actually) its entire infrastructure. There will be a completely brand new domain/AD set up that's totally unrelated to the old one. At the same time, we also plan to migrate
    all emails (previously hosted locally on Exchange 2007) to Office 365 and get rid of local exchange. Now because we will set up new domain, we do not want to carry over the older AD to the cloud, hence we will not use the "Staged Migration". 
    So the plan is to to use "Cutover" migration first, which means all authentications will become Office 365 managed. That's fine for now. But later, after we set up our new domain and AD controller etc, we'd like to have Exchange Online switch back
    to syncing with our new on-premise AD. We'd also like to consider the AD Federation Services if it's not too complicated to set up.
    Your advice on this would be greatly appreciated!

    In principle, you cannot sync back from the cloud AD to the on-prem, yet. But you can take advantage of the soft-matching mechanism once you have the new AD in place:
    http://support.microsoft.com/kb/2641663
    Be careful though, as the moment you turn on Dirsync, all the matching users in the cloud will have their attributes overwritten. A very good idea is to do an 'export' of the cloud AD first, using the WAAD module for PowerShell and the Get-MsolUser cmdlets,
    which you can then use to compare or import data in the new on-prem AD. Some links:
    http://technet.microsoft.com/en-us/library/hh974317.aspx
    http://msdn.microsoft.com/en-us/library/azure/dn194133.aspx

  • Any way to get all users's user profile proeprty using CSOM c# for sharepoint online - office 365?

    Any way to get all users's user profile proeprty using CSOM c# for sharepoint online - office 365?

    Since CSOM provides methods for operations related to people per
    user scope, you could retrieve all site users first using SP.Web.siteUsers
    property. and then use SP.UserProfiles.PeopleManager.getUserProfilePropertyFor
    Method to get property.
    [custom.development]

  • Office 365 / Exchange Online - Hybrid Setup - On Premise User cannot see calendar of an Exchange Online User.

    Hi All, 
    The below will help if:
    You have a hybrid setup and cannot see Free/Busy info from an On Premise user for anyone on Office 365 / Exchange Online.
    You have your network firewall configured to allow your Exchange servers out through the proxy for O365/EXO url's
    - Get hold of SysInternals PSEXEC from Microsoft. 
    Run PSEXEC -i -s C"\Program Files (x86)\Internet Explorer\iexplore.exe"  (This opens Internet Explorer as the SYSTEM account)
    Goto Internet Options > Connections > LAN Settings and untick the "Automatically Detect Settings"
    Had this bouncing around at Microsoft for a few days until one of the guys tried this and it worked immediately.

    Forgot to mention, the PSEXEC command needs to be run as an Administrator
    Run PSEXEC -i -s C"\Program Files (x86)\Internet Explorer\iexplore.exe"  (This opens Internet Explorer as the SYSTEM account)
    Goto Internet Options > Connections > LAN Settings and untick the "Automatically Detect Settings"

  • Exchange Online: Migrating User Data to New Employee

    I'm sorry if this has been discussed already but all my searches for migrating, moving, or transferring all pointed to discussions regarding entire systems rather than users on the same system.  Further, I'm not asking anyone to write a script for me,
    I'm just trying to figure out if I'm re-inventing the wheel and just haven't found an existing script or am just plain doing it wrong.
    We are using Exchange Online (Office 365) without any sort of AD sync.  When a user leaves the company their addresses and mailbox data all need to get moved to their replacement and/or supervisor.  Sometimes, we have to temporarily remove the
    destination user's quotas to be able to receive this influx of data. These individual steps can be done via the admin console but I'm wondering if anyone has put it all together in a script.
      Thanks,
       Bryan

    Now, it doesn't surprise me that no one had written that _exact_ script.  I'm not asking anyone to and am capable to doing it myself provided it's possible via the various cmdlets.  However, I am surprised something along those lines hasn't been
    created.  All my searches yielded thousands of results dealing with the migration from one version of Exchange to another.  Yes, you can use Outlook but even for a medium sized company like the one I work at that is cumbersome and time consuming.
    You will not find the exact script but there are many scripts in the Gallery showing how to create and mange users. You will need to learn PowerShell to understand these as well as learn how to use the Exchange shell.
    Start small.  Try and create a script that connects to Exchange and retrives the user in question.  Liook at how PowerShell uses "Get" and "Set" commands to update objects.  In an afternoon of truying the examples you will have enough information
    to write your script and maybe ask a specific question when you get confused.
    Here are a whole list of articles on how to use PowerShell with Office 365.
    http://blogs.technet.com/b/heyscriptingguy/archive/tags/office+365/default.aspx
    ¯\_(ツ)_/¯

  • How to retrieve all users in the portal with UME API

    Hi everybody,
    I would like to know how to retrieve all the users from a portal, which uses LDAP as a source (there are users created in the portal as well)
    My code snippet is :
    IUserFactory userFactory = UMFactory.getUserFactory();
    UserSearchFilter searchFilter = userFactory.getUserSearchFilter();
    searchFilter.setDisplayName("*", ISearchAttribute.LIKE_OPERATOR, false);
    ISearchResult searchResult = userFactory.searchUsers(searchFilter);
    My problem is that with the code above, only the users created in the portal are displayed, and no LDAP users.
    Does someone know how to retrieve all the users whatever is the source?
    Regards
    Renaud

    prakash's code should work.
    however, mine code below doesn't user a search filter. it retrieves everyuser including users like indexadmin etc. Note:
    result.next().toString();
    returns a weird uniqueID used in the portal world.
    getUniqueName()
    gives your the usernames (sAMAccountName in Microsoft AD) people use to logon to the portal.
    try {
      IUserFactory uf = UMFactory.getUserFactory();
      ISearchResult result = uf.getUniqueIDs();
      while (result.hasNext()) {
        String uniqueid = result.next().toString();
        IUser user = uf.getUser(uniqueid);
        String userid = user.getUniqueName();
    } catch(Exception e) {
      //systemout

Maybe you are looking for

  • Error handling function: ORA-20001: get_dbms_sql_cursor error:ORA-00942: table or view does not exist  is not trapped. Why?

    Why APEX 4.1 Error handling function does not trap  the error of missing table? Say, I create simple application with single IR report page and I also assign standard simple error handling function. Function works perfectly, except but this case: If

  • READ_LINKS_OF_BINRELS instead of SREL_GET_NEXT_RELATIONS

    I am updating a report from 4.7 to 5.0, and I learned that function module SREL_GET_NEXT_RELATIONS will not work for me in 5.0. I am trying to use cl_binary_relation=>read_links_of_binrels instead, and then call FM SO_OBJECT_READ. In code for 4.7 I u

  • JSP- EJB Communication

    I have a client-server application where my client is an applet and the server is an EJB. The HTML code to launch the applet is dynamically generated by a JSP page. Now i want this JSP page to be able to communicate with the EJB. What i need is that

  • SOP: How to update ratio values

    Hi everyone, I have defined an Information Structure with some characteristics and ratios, all of them associated to some ZTable fields. Well, I would be very grateful whether someone could tell how to update ratio values in my Information Structure.

  • Xsan with ADIC IRIX client

    I installed an IRIX client on SGI machine but can't mount or start Xsan "file system" on the IRIX machine. I get "missing configuration file" error using cvadmin start command. I couldn't find in ADIC or Apple manuals info whether I need to copy the