Tuesday, February 19, 2019

How to unsubscribe from a Mailing list using the Graph API

One of the features that is currently in beta in the Microsoft Graph API is an operation that will let you unsubscribe from any mailing list that supports the List-Unsubscribe header in a message that complies with RFC-2369 (https://docs.microsoft.com/en-us/graph/api/message-unsubscribe?view=graph-rest-beta).

This can have a number of uses one that does come to mind is when you have staff that are leaving the company (or even taking an extended break where they won't be reading their email) and they have signed up to quite of number of mailing lists. As part of your deprovisioning process you can include a script that will unsubscribe from the emails in a Mailbox before you remove the account instead of deleting and hoping the NDR's do it for you.

The RFC state the following for List-Unsubscribe

3.2. List-Unsubscribe

   The List-Unsubscribe field describes the command (preferably using
   mail) to directly unsubscribe the user (removing them from the list).


     List-Unsubscribe: (Use this command to get off the list)
     List-Unsubscribe: ,
Notably the word preferably is used in the RFC which means that from a implementation standpoint you don't have to have an unsubscribe email address to comply with this RFC. One example of this is  LinkedIn which only has URL's for the unsubscribe which requires you click a checkbox etc to unsubscribe which does nullify the usefulness of this somewhat.

To use this operation is pretty simple all you need is the Id of the mail you want to unsubscribe to and then you do a post on the unsubscribe nav


I've created a simple ADAL graph script that gets a unique list of un-subscribable  email for the last 1000 emails in a Mailbox and then runs the unsubscribe method on those emails and posted It https://github.com/gscales/Powershell-Scripts/blob/master/Unsubscribe-Emails.ps1.

 I've also added support for  this into my Exch-Rest module which is available from the PowerShell Gallery and GitHub

To show the unsubscribe information for the last 100 messages in the Inbox use

Get-EXRWellKnownFolderItems -MailboxName gscales@datarumble.com -WellKnownFolder Inbox -MessageCount 100 -ReturnUnsubscribeData | select Subject,unsub* | fl

To process all the email from the last 7 days and unsubscribe for that using something like

        $UnSubribeHash = @{}
        -Filter ("receivedDateTime ge " + [DateTime]::Now.AddDays(-7).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) -ReturnUnsubscribeData | where-object {$_.unsubscribeEnabled -eq $True} | ForEach-Object{
            $Message = $_
                foreach($Entry in $Message.unsubscribeData){
                            Invoke-EXRUnsubscribeEmail -ItemRESTURI $Message.ItemRESTURI