Search code examples
c#emailoutlookexchange-serverexchangewebservices

EWS API - How to block (MarkAsJunk) an E-Mail by domain and not sender?


I am using following code to mark an e-mail as junk with the "MarkAsJunk" method which works fine for blocking the full sender ([email protected]) as whole:

private static void MarkMessageAsJunk(ExchangeService service, ItemId messageId, bool isJunk, bool moveItem)
{
    List<ItemId> junkItemIds = new List<ItemId>();
    junkItemIds.Add(messageId);
    ServiceResponseCollection<MarkAsJunkResponse> responseCollection = null;
    try
    {
        // If isJunk is true, the sender of the email message is added to 
        // the Blocked Senders List. If isJunk is false, the sender is removed
        // from the list (if present).
        responseCollection = service.MarkAsJunk(junkItemIds, isJunk, moveItem);
    }
    catch (ServiceResponseException ex)
    {
        Console.WriteLine("Error marking item as junk: {0}", ex.ErrorCode);
        return;
    }
    foreach (MarkAsJunkResponse response in responseCollection)
    {
        if (response.Result == ServiceResult.Success)
        {
            Console.WriteLine("Successfully marked message as {0}junk.", isJunk ? "": "NOT ");
            if (moveItem)
            {
                Console.WriteLine("New item ID: {0}", response.MovedItemId.ToString());
            }
        }
        else
        {
            Console.WriteLine("[{0}]: {1}", response.Result.ToString(),
                response.ErrorCode.ToString());
        }
    }
}

When I check the Junk Settings within Outlook I can see the blocked sender. In Outlook I am able to add a new entry by only defining the domain like "@xyz.com" or even just "xyz.com" works. How can I do it with EWS? Would I somehow need to be able to modify the sender / from address (remove everything before the @) from the messageId generated mail, is this even possible? Does anybody has an idea?

Thanks a lot.


Solution

  • Apart from what you are using there isn't anything in EWS that allows you to manage the SafeSender list in a Mailbox easily. Underlying its stored on an extended rule object so you could use EWS to modify the extended properties directly eg PidTagExtendedRuleMessageCondition and the Blob format is described here MS-OXCSPAM https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcspam/70e414e0-1798-47a0-a439-9ee3dc641a9e and in MS-OXORULE respectively (if you use OutlookSpy of MFCMapi you should be able to see the Junk Email Configuration object)

    An easier option would be to use the the cmdlets instead https://learn.microsoft.com/en-us/microsoft-365/security/office-365-security/configure-junk-email-settings-on-exo-mailboxes?view=o365-worldwide

    One other option would be to use MAPI and Redemption which makes this easier eg https://www.dimastr.com/redemption/rdojunkemailoptions.htm