How can I use powershell to count emails by sender for a large (160k+) O365 mailbox?

Danny S 0 Reputation points
2023-05-07T17:40:22.2633333+00:00

I have a large mailbox (160k+ emails) on Microsoft 365 Business Premium that's running out of space.

The outlook clients (online and mac desktop) are hopeless for grouping and deleting emails in bulk, so I want to run powershell scripts (or some other kind of code/scripts) that will:

  • Give me a summary of the count of emails per sender, ideally with a first and last sent date, so I can work out which senders has sent the most emails to the mailbox.
  • Allow me to delete all the emails from a given sender (or list of senders in an array or csv file) so I can free up space in the mailbox.

I am a developer but I don't really know powershell - I've tried Get-MessageTrace but it's limited to the last 10 days, and I can't work out if Start-HistoricalSearch will be able to give me what I need.

I'm happy to try another method other than powershell if there's another approach.

Exchange Online
Exchange Online
A cloud-based service included in Microsoft 365, delivering scalable messaging and collaboration features with simplified management and automatic updates.
Exchange | Exchange Server | Development
Windows for business | Windows Server | User experience | PowerShell
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 48,036 Reputation points
    2023-05-07T18:12:56.8+00:00

    For an on-premises Exchange we used to use MAPI (i.e., the Outlook COM API). With O365 your best bet is to use Microsoft Graph: https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/office-365-rest-apis-for-mail-calendars-and-contacts

    There are PowerShell cmdlets for this: https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.mail/?view=graph-powershell-1.0

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.