EWS v2

Exchange Web Services and Office 365 (mail).

Email · Microsoft Exchange On-Premise

Details

IDEWS v2
ProviderMicrosoft
CategoryEmail
From Version5.0.0
Docker Imagedemisto/py-ews:5.6.0.12072219
Supported ModulesAgentix Cloud Runtime Security Cloud Posture Security XSIAM EDR Cortex Cloud

README

Exchange Web Services (EWS) provides the functionality to enable client applications to communicate with the Exchange server. EWS provides access to much of the same data that is made available through Microsoft Office Outlook.

The EWS v2 integration implants EWS leading services. The integration allows getting information on emails and activities in a target mailbox, and some active operations on the mailbox such as deleting emails and attachments or moving emails from folder to folder.

Note: Starting from pack version 2.0.0 the EWS v2 integration requires the Exchange server to support TLS v1.2 and up in order to connect.

Multi-Factor Authentication (MFA)
EWS v2 does not support Multi-Factor Authentication (MFA).

If using MFA, use EWS O365 (see https://xsoar.pan.dev/docs/reference/integrations/ewso365)

or if you have Graph Outlook use O365 Outlook Mail (Using Graph API) (see https://xsoar.pan.dev/docs/reference/integrations/microsoft-graph-mail)

or O365 Outlook Mail Single User (Using Graph API) (see https://xsoar.pan.dev/docs/reference/integrations/microsoft-graph-mail-single-user).

EWS v2 Playbooks

  • Office 365 Search and Delete
  • Search And Delete Emails - EWS
  • Get Original Email - EWS
  • Process Email - EWS

Use Cases

The EWS integration can be used for the following use cases:

  • Monitor a specific email account and create incidents from incoming emails to the defined folder.
    Follow the instructions in the Fetched Incidents Data section.
  • Search for an email message across mailboxes and folders.
    This can be achieved in the following ways:
    • Use the ews-search-mailboxes command to search for all emails in a specific scope of mailboxes. Use the filter argument to narrow the search for emails sent from a specific account and more.
    • Use the ews-search-mailbox command to search for all emails in a specific folder within the target mailbox. Use the query argument to narrow the search for emails sent from a specific account and more.

    Both of these commands retrieve the ItemID field for each email item listed in the results. TheItemID can be used in the ews-get-items command in order to get more information about the email item itself.
    For instance, use the ews-search-mailboxes command to hunt for emails that were marked as malicious in prior investigations, across organization mailboxes. Focus your hunt on emails sent from a specific mail account, emails with a specific subject and more.

  • Get email attachment information. Use the ews-get-attachment command to retrieve information on one attachment or all attachments of a message at once. It supports both file attachments and item attachments (e.g., email messages).
  • Delete email items from a mailbox. First, make sure you obtain the email item ID. The item ID can be obtained with one of the integration’s search commands. Use the ews-delete-items command to delete one or more items from the target mailbox in a single action. A less common use case is to remove emails that were marked as malicious from a user’s mailbox. You can delete the items permanently (hard delete), or delete the items (soft delete), so they can be recovered by running the ews-recover-messages command.
  • Send notifications to external users.
  • Send an email asking for a response to be returned as part of a playbook. See Receiving an email reply

Configure EWS v2 in Cortex

Parameter Required
Email address True
Password True
Email address from which to fetch incidents True
Name of the folder from which to fetch incidents (supports Exchange Folder ID and sub-folders e.g. Inbox/Phishing) True
Public Folder False
Has impersonation rights False
Use system proxy settings False
Fetch incidents False
First fetch timestamp (<number> <time unit>, e.g., 12 hours, 7 days) False
Mark fetched emails as read False
Incident type False
┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉
‎ Manual Mode
Exchange Server Hostname or IP address
False
DOMAIN\USERNAME (e.g. DEMISTO.INT\admin) False
Exchange Server Version (On-Premise only. Supported versions: 2007, 2010, 2010_SP2, 2013, 2016, and 2019) False
Trust any certificate (not secure) False
┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉
‎ Advanced Mode
Override Authentication Type (NTLM, Basic, or Digest).
False
Timeout (in seconds) for HTTP requests to Exchange Server False
Max incidents per fetch False
Run as a separate process (protects against memory depletion) False
Skip unparsable emails during fetch incidents False

Fetched Incidents Data

The integration imports email messages from the destination folder in the target mailbox as incidents. If the message contains any attachments, they are uploaded to the War Room as files. If the attachment is an email, Cortex XSOAR fetches information about the attached email and downloads all of its attachments (if there are any) as files.

To use Fetch incidents, configure a new instance and select the Fetches incidents option in the instance settings.

IMPORTANT: The initial fetch interval is the previous 10 minutes. If no emails were fetched before from the destination folder, all emails from 10 minutes prior to the instance configuration and up to the current time will be fetched. Additionally, moving messages manually to the destination folder will not trigger a fetch incident. Define rules on phishing/target mailbox instead of moving messages manually.

You can configure the First fetch timestamp field to determine how much time back you want to fetch incidents.

Notice that it might require you to set the Timeout field to a higher value.

Pay special attention to the following fields in the instance settings:

  • Email address from which to fetch incidents – mailbox to fetch incidents from.

  • Name of the folder from which to fetch incidents – use this field to configure the destination folder from where emails should be fetched. The default is Inbox folder. Please note, if Exchange is configured with an international flavor, Inbox will be named according to the configured language.

  • Has impersonation rights – mark this option if you set the target mailbox to an account different than your personal account. Otherwise Delegation access will be used instead of Impersonation.
    Find more information on impersonation or delegation rights in the Additional Information section.

Commands

You can execute these commands from the CLI, as part of an automation, or in a playbook.
After you successfully execute a command, a DBot message appears in the War Room with the command details.

ews-get-attachment


Retrieves the actual attachments from an item (email message). To get all attachments for a message, only specify the item-id argument.

Base Command

ews-get-attachment

Input

Argument Name Description Required
item-id The ID of the email message for which to get the attachments. Required
target-mailbox The mailbox in which this attachment was found. If empty, the default mailbox is used. Otherwise the user might require impersonation rights to this mailbox. Optional
attachment-ids The attachments ids to get. If none - all attachments will be retrieve from the message. Support multiple attachments with comma-separated value or array. Optional

Context Output

Path Type Description
EWS.Items.FileAttachments.attachmentId string The attachment ID. Used for file attachments only.
EWS.Items.FileAttachments.attachmentName string The attachment name. Used for file attachments only.
EWS.Items.FileAttachments.attachmentSHA256 string The SHA256 hash of the attached file.
EWS.Items.FileAttachments.attachmentLastModifiedTime date The attachment last modified time. Used for file attachments only.
EWS.Items.ItemAttachments.datetimeCreated date The created time of the attached email.
EWS.Items.ItemAttachments.datetimeReceived date The received time of the attached email.
EWS.Items.ItemAttachments.datetimeSent date The sent time of the attached email.
EWS.Items.ItemAttachments.receivedBy string The received by address of the attached email.
EWS.Items.ItemAttachments.subject string The subject of the attached email.
EWS.Items.ItemAttachments.textBody string The body of the attached email (as text).
EWS.Items.ItemAttachments.headers Unknown The headers of the attached email.
EWS.Items.ItemAttachments.hasAttachments boolean Whether the attached email has attachments.
EWS.Items.ItemAttachments.itemId string The attached email item ID.
EWS.Items.ItemAttachments.toRecipients Unknown A list of recipient email addresses for the attached email.
EWS.Items.ItemAttachments.body string The body of the attached email (as HTML).
EWS.Items.ItemAttachments.attachmentSHA256 string The SHA256 hash of the attached email (as EML file).
EWS.Items.ItemAttachments.FileAttachments.attachmentSHA256 string SHA256 hash of the attached files inside of the attached email.
EWS.Items.ItemAttachments.ItemAttachments.attachmentSHA256 string SHA256 hash of the attached emails inside of the attached email.
EWS.Items.ItemAttachments.isRead String The read status of the attachment.

Command Example

!ews-get-attachment item-id=BBFDShfdafFSDF3FADR3434DFASDFADAFDADFADFCJebinpkUAAAfxuiVAAA= target-mailbox=test@demistodev.onmicrosoft.com

Context Example

{
  "EWS": {
    "Items": {
      "ItemAttachments": {
        "originalItemId": "BBFDShfdafFSDF3FADR3434DFASDFADAFDADFADFCJebinpkUAAAfxuiVAAA=",
        "attachmentSize": 2956,
        "receivedBy": "test@demistodev.onmicrosoft.com",
        "size": 28852,
        "author": "test2@demistodev.onmicrosoft.com",
        "attachmentLastModifiedTime": "2019-08-11T15:01:30+00:00",
        "subject": "Moving Email between mailboxes",
        "body": "Some text inside",
        "datetimeCreated": "2019-08-11T15:01:47Z",
        "importance": "Normal",
        "attachmentType": "ItemAttachment",
        "toRecipients": [
          "test@demistodev.onmicrosoft.com"
        ],
        "mailbox": "test@demistodev.onmicrosoft.com",
        "isRead": false,
        "attachmentIsInline": false,
        "datetimeSent": "2019-08-07T12:50:19Z",
        "lastModifiedTime": "2019-08-11T15:01:30Z",
        "sender": "test2@demistodev.onmicrosoft.com",
        "attachmentName": "Moving Email between mailboxes",
        "datetimeReceived": "2019-08-07T12:50:20Z",
        "attachmentSHA256": "119e27b28dc81bdfd4f498d44bd7a6d553a74ee03bdc83e6255a53",
        "hasAttachments": false,
        "headers": [
          {
            "name": "Subject",
            "value": "Moving Email between mailboxes"
          }
        ],
        "attachmentId": "BBFDShfdafFSDF3FADR3434DFASDFADAFDADFADFCJebinpkUAAAfxuiVAAABEgAQAOpEfpzDB4dFkZ+/K4XSj44=",
        "messageId": "&lt;message_id&gt;"
      }
    }
  }
}

ews-delete-attachment


Deletes the attachments of an item (email message).

Base Command

ews-delete-attachment

Input

Argument Name Description Required
item-id The ID of the email message for which to delete attachments. Required
target-mailbox The mailbox in which this attachment was found. If empty, the default mailbox is used. Otherwise the user might require impersonation rights to this mailbox. Optional
attachment-ids A CSV list (or array) of attachment IDs to delete. If empty, all attachments will be deleted from the message. Optional

Context Output

Path Type Description
EWS.Items.FileAttachments.attachmentId string The ID of the deleted attachment, in case of file attachment.
EWS.Items.ItemAttachments.attachmentId string The ID of the deleted attachment, in case of other attachment (for example, “email”).
EWS.Items.FileAttachments.action string The deletion action in case of file attachment. This is a constant value: ‘deleted’.
EWS.Items.ItemAttachments.action string The deletion action in case of other attachment (for example, “email”). This is a constant value: ‘deleted’.

Command Example

!ews-delete-attachment item-id=AAMkADQ0NmwBGAAAAAAA4kxh+ed3JTJPMPXU3wX3aBwCyyVyFtlsUQZfBJjfaljfAFDVSDinpkUAAAfxxd9AAA= target-mailbox=test@demistodev.onmicrosoft.com

Human Readable Output

action attachmentId
deleted AAMkADQ0NmwBGAAAAAAA4kxh+ed3JTJPMPXU3wX3aBwCyyVyFtlsUQZfBJjfaljfAFDVSDinpkUAAAfxxd9AAABEgAQAIUht2vrOdErec33=

Context Example

{
    "EWS": {
        "Items": {
            "FileAttachments": {
                "action": "deleted",
                "attachmentId": "AAMkADQ0NmwBGAAAAAAA4kxh+ed3JTJPMPXU3wX3aBwCyyVyFtlsUQZfBJjfaljfAFDVSDinpkUAAAfxxd9AAABEgAQAIUht2vrOdErec33="
            }
        }
    }
}

ews-get-searchable-mailboxes


Returns a list of searchable mailboxes. This command requires eDiscovery permissions to the Exchange Server. For more information, see the EWSv2 integration documentation.

Base Command

ews-get-searchable-mailboxes

Input

There are no input arguments for this command.

Context Output

Path Type Description
EWS.Mailboxes.mailbox string Addresses of the searchable mailboxes.
EWS.Mailboxes.mailboxId string IDs of the searchable mailboxes.
EWS.Mailboxes.displayName string The email display name.
EWS.Mailboxes.isExternal boolean Whether the mailbox is external.
EWS.Mailboxes.externalEmailAddress string The external email address.

Command Example


#### Human Readable Output

>|displayName|isExternal|mailbox|mailboxId|
>|---|---|---|--- |
>| test | false |<test@demistodev.onmicrosoft.com> | /o=Exchange***/ou=Exchange Administrative Group ()/cn=**/cn=**-**|

#### Context Example

```json
{
    "EWS": {
        "Mailboxes": [
            {
                "mailbox": "test@demistodev.onmicrosoft.com", 
                "displayName": "test", 
                "mailboxId": "/o=Exchange***/ou=Exchange Administrative Group ()/cn=**/cn=**-**", 
                "isExternal": "false"
            }
        ]
    }
}

ews-search-mailboxes


Searches over multiple mailboxes or all Exchange mailboxes. Use either the mailbox-search-scope command or the email-addresses command to search specific mailboxes. This command requires eDiscovery permissions to the Exchange Server. For more information, see the EWS v2 integration documentation.

The number of mailboxes to search in may be limited by Microsoft Exchange. See here for more information.

Base Command

ews-search-mailboxes

Input

Argument Name Description Required
filter The filter query to search. Required
mailbox-search-scope The mailbox IDs to search. If empty, all mailboxes are searched. Optional
limit Maximum number of results to return. Default is 250. Optional
email_addresses CSV list or array of email addresses. Optional

Context Output

Path Type Description
EWS.Items.itemId string The item ID.
EWS.Items.mailbox string The mailbox address where the item was found.
EWS.Items.subject string The subject of the email.
EWS.Items.toRecipients Unknown List of recipient email addresses.
EWS.Items.sender string Sender email address.
EWS.Items.hasAttachments boolean Whether the email has attachments?
EWS.Items.datetimeSent date Sent time of the email.
EWS.Items.datetimeReceived date Received time of the email.

Command Example

!ews-search-mailboxes filter="subject:Test" limit=1

Human Readable Output

datetimeReceived datetimeSent hasAttachments itemId mailbox sender subject toRecipients  
2019-08-11T11:00:28Z 2019-08-11T11:00:28Z false AAMkAGY3OTQyMzMzLWYxNjktNDE0My05NmZhLWQ5MGY1YjIyNzBkNABGACASFAACYCKjWAnXDFrfsdhdnfkanpAAA= test2@demistodev.onmicrosoft.com John Smith test report dem@demistodev.onmicrosoft.com  

Context Example

{
    "EWS": {
        "Items": {
            "itemId": "AAMkAGY3OTQyMzMzLWYxNjktNDE0My05NmZhLWQ5MGY1YjIyNzBkNABGACASFAACYCKjWAnXDFrfsdhdnfkanpAAA=", 
            "sender": "John Smith", 
            "datetimeReceived": "2019-08-11T11:00:28Z", 
            "hasAttachments": "false", 
            "toRecipients": [
                "dem@demistodev.onmicrosoft.com"
            ], 
            "mailbox": "test2@demistodev.onmicrosoft.com", 
            "datetimeSent": "2019-08-11T11:00:28Z", 
            "subject": "test report "
        }
    }
}

ews-move-item


Move an item to different folder in the mailbox.

Base Command

ews-move-item

Input

Argument Name Description Required
item-id The ID of the item to move. Required
target-folder-path The path to the folder to which to move the item. Complex paths are supported, for example, “Inbox\Phishing”. Required
target-mailbox The mailbox on which to run the command. Optional
is-public Whether the target folder is a public folder. Possible values are: True, False. Optional

Context Output

Path Type Description
EWS.Items.newItemID string The item ID after move.
EWS.Items.messageID string The item message ID.
EWS.Items.itemId string The original item ID.
EWS.Items.action string The action taken. The value will be “moved”.

ews-delete-items


Delete items from mailbox. This command requires eDiscovery permissions to the Exchange Server. For more information, see the EWSv2 integration documentation.

Base Command

ews-delete-items

Input

Argument Name Description Required
item-ids The item IDs to delete. Required
delete-type Deletion type. Can be “trash”, “soft”, or “hard”. Default is soft. Required
target-mailbox The mailbox on which to run the command. Optional

Context Output

Path Type Description
EWS.Items.itemId string The deleted item ID.
EWS.Items.messageId string The deleted message ID.
EWS.Items.action string The deletion action. Can be ‘trash-deleted’, ‘soft-deleted’, or ‘hard-deleted’.

Command Example

!ews-delete-items item-ids=VWAFA3hmZjdmNTZjNTMxNwBGAAAAAAA4kxh+ed3JTJPMPXU3wX3aBwCyyVyFtlsUQZfBJebinpkUAAABjKMGAACyw+kAAA= delete-type=soft target-mailbox=test@demistodev.onmicrosoft.com

Human Readable Output

action itemId messageId
soft-deleted VWAFA3hmZjdmNTZjNTMxNwBGAAAAAAA4kxh+ed3JTJPMPXU3wX3aBwCyyVyFtlsUQZfBJebinpkUAAABjKMGAACyw+kAAA=

Context Example

{
    "EWS": {
        "Items": {
            "action": "soft-deleted", 
            "itemId": "VWAFA3hmZjdmNTZjNTMxNwBGAAAAAAA4kxh+ed3JTJPMPXU3wX3aBwCyyVyFtlsUQZfBJebinpkUAAABjKMGAACyw+kAAA=", 
            "messageId": "&lt;messaage_id&gt;"
        }
    }
}

ews-search-mailbox


Searches for items in the specified mailbox. Specific permissions are needed for this operation to search in a target mailbox other than the default.

Base Command

ews-search-mailbox

Input

Argument Name Description Required
query The search query string. For more information about the query syntax, see the Microsoft documentation: https://msdn.microsoft.com/en-us/library/ee693615.aspx. Optional
folder-path The folder path in which to search. If empty, searches all the folders in the mailbox. Optional
limit Maximum number of results to return. Default is 100. Optional
target-mailbox The mailbox on which to apply the search. Optional
is-public Whether the folder is a Public Folder?. Possible values are: True, False. Optional
message-id The message ID of the email. This will be ignored if a query argument is provided. Optional
selected-fields A CSV list of fields to retrieve. Possible values are: . Default is all. Optional
surround_id_with_angle_brackets Whether to surround the message ID with angle brackets (<>) if it does not exist. Default is ‘True’. Optional

Context Output

Path Type Description
EWS.Items.itemId string The email item ID.
EWS.Items.hasAttachments boolean Whether the email has attachments.
EWS.Items.datetimeReceived date Received time of the email.
EWS.Items.datetimeSent date Sent time of the email.
EWS.Items.headers Unknown Email headers (list).
EWS.Items.sender string Sender email address of the email.
EWS.Items.subject string Subject of the email.
EWS.Items.textBody string Body of the email (as text).
EWS.Items.size number Email size.
EWS.Items.toRecipients Unknown List of email recipients addresses.
EWS.Items.receivedBy Unknown Email received by address.
EWS.Items.messageId string Email message ID.
EWS.Items.body string Body of the email (as HTML).
EWS.Items.FileAttachments.attachmentId unknown Attachment ID of the file attachment.
EWS.Items.ItemAttachments.attachmentId unknown Attachment ID of the item attachment.
EWS.Items.FileAttachments.attachmentName unknown Attachment name of the file attachment.
EWS.Items.ItemAttachments.attachmentName unknown Attachment name of the item attachment.
EWS.Items.isRead String The read status of the email.

Command Example

!ews-search-mailbox query="subject:"Get Attachment Email" target-mailbox=test@demistodev.onmicrosoft.com limit=1

Human Readable Output

sender subject hasAttachments datetimeReceived receivedBy author toRecipients
test2@demistodev.onmicrosoft.com Get Attachment Email true 2019-08-11T10:57:37Z test@demistodev.onmicrosoft.com test2@demistodev.onmicrosoft.com test@demistodev.onmicrosoft.com

Context Example

{
    "EWS": {
        "Items": {
            "body": "&lt;html&gt;\r\n&lt;head&gt;\r\n&lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"&gt;\r\n&lt;style type=\"text/css\" style=\"display:none;\"&gt;&lt;!-- P {margin-top:0;margin-bottom:0;} --&gt;&lt;/style&gt;\r\n&lt;/head&gt;\r\n&lt;body dir=\"ltr\"&gt;\r\n&lt;div id=\"divtagrapper\" style=\"font-size:12pt;color:#000000;font-family:Calibri,Helvetica,sans-serif;\" dir=\"ltr\"&gt;\r\n&lt;p style=\"margin-top:0;margin-bottom:0\"&gt;Some text inside email&lt;/p&gt;\r\n&lt;/div&gt;\r\n&lt;/body&gt;\r\n&lt;/html&gt;\r\n", 
            "itemId": "AAMkADQ0NmFFijer3FFmNTZjNTMxNwBGAAAAAAFSAAfxw+jAAA=", 
            "toRecipients": [
                "test@demistodev.onmicrosoft.com"
            ], 
            "datetimeCreated": "2019-08-11T10:57:37Z", 
            "datetimeReceived": "2019-08-11T10:57:37Z", 
            "author": "test2@demistodev.onmicrosoft.com", 
            "hasAttachments": true, 
            "size": 30455, 
            "subject": "Get Attachment Email", 
            "FileAttachments": [
                {
                    "attachmentName": "atta1.rtf", 
                    "attachmentSHA256": "csfd81097bc049fbcff6e637ade0407a00308bfdfa339e31a44a1c4e98f28ce36e4f", 
                    "attachmentType": "FileAttachment", 
                    "attachmentSize": 555, 
                    "attachmentId": "AAMkADQ0NmFkODFkLWQ4MDEtNDE4Mi1hN2NkLThmZjdmNTZjNTMxNwBGAAAAAAA4kxh+ed3JTJPMPXU3wX3aBwCyyVyFtlsUQZfBJebinpkUAAABjKMGAACyyVyFtlsUQZfBJebinpkUAAAfxw+jAAABEgAQAEyq1TB2nKBLpKUiFUJ5Geg=", 
                    "attachmentIsInline": false, 
                    "attachmentLastModifiedTime": "2019-08-11T11:06:02+00:00", 
                    "attachmentContentLocation": null, 
                    "attachmentContentType": "text/rtf", 
                    "originalItemId": "AAMkADQ0NmFFijer3FFmNTZjNTMxNwBGAAAAAAFSAAfxw+jAAA=", 
                    "attachmentContentId": null
                }
            ], 
            "headers": [
                {
                    "name": "Subject", 
                    "value": "Get Attachment Email"
                }
            ], 
            "isRead": true, 
            "messageId": "&lt;mesage_id&gt;", 
            "receivedBy": "test@demistodev.onmicrosoft.com", 
            "datetimeSent": "2019-08-11T10:57:36Z", 
            "lastModifiedTime": "2019-08-11T11:13:59Z", 
            "mailbox": "test@demistodev.onmicrosoft.com", 
            "importance": "Normal", 
            "textBody": "Some text inside email\r\n", 
            "sender": "test2@demistodev.onmicrosoft.com"
        }
    }
}

ews-get-contacts


Retrieves contacts for a specified mailbox.

Base Command

ews-get-contacts

Input

Argument Name Description Required
target-mailbox The mailbox for which to retrieve the contacts. Optional
limit Maximum number of results to return. Default is 100. Optional

Context Output

Path Type Description
Account.Email.EwsContacts.displayName Unknown The contact name.
Account.Email.EwsContacts.lastModifiedTime Unknown The time that the contact was last modified.
Account.Email.EwsContacts.emailAddresses Unknown Phone numbers of the contact.
Account.Email.EwsContacts.physicalAddresses Unknown Physical addresses of the contact.
Account.Email.EwsContacts.phoneNumbers.phoneNumber Unknown Email addresses of the contact.

Command Example

!ews-get-contacts limit="1"

Human Readable Output

changekey culture datetimeCreated datetimeReceived datetimeSent displayName emailAddresses fileAs fileAsMapping givenName id importance itemClass lastModifiedName lastModifiedTime postalAddressIndex sensitivity subject uniqueBody webClientReadFormQueryString
EABYACAADcsxRwRjq/zTrN6vWSzKAK1Dl3N en-US 2019-08-05T12:35:36Z 2019-08-05T12:35:36Z 2019-08-05T12:35:36Z Contact Name some@dev.microsoft.com Contact Name LastCommaFirst Contact Name AHSNNK3NQNcasnc3SAS/zTrN6vWSzK4OWAAAAAAEOAADrxRwRjq/zTrNFSsfsfVWAAK1KsF3AAA= Normal IPM.Contact John Smith 2019-08-05T12:35:36Z None Normal Contact Name   https://outlook.office365.com/owa/?ItemID=***

Context Example

{
    "Account.Email": [
        {
            "itemClass": "IPM.Contact", 
            "lastModifiedName": "John Smith", 
            "displayName": "Contact Name", 
            "datetimeCreated": "2019-08-05T12:35:36Z", 
            "datetimeReceived": "2019-08-05T12:35:36Z", 
            "fileAsMapping": "LastCommaFirst", 
            "importance": "Normal", 
            "sensitivity": "Normal", 
            "postalAddressIndex": "None", 
            "webClientReadFormQueryString": "https://outlook.office365.com/owa/?ItemID=***", 
            "uniqueBody": "&lt;html&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;", 
            "fileAs": "Contact Name", 
            "culture": "en-US", 
            "changekey": "EABYACAADcsxRwRjq/zTrN6vWSzKAK1Dl3N", 
            "lastModifiedTime": "2019-08-05T12:35:36Z", 
            "datetimeSent": "2019-08-05T12:35:36Z", 
            "emailAddresses": [
                "some@dev.microsoft.com"
            ], 
            "givenName": "Contact Name", 
            "id": "AHSNNK3NQNcasnc3SAS/zTrN6vWSzK4OWAAAAAAEOAADrxRwRjq/zTrNFSsfsfVWAAK1KsF3AAA=", 
            "subject": "Contact Name"
        }
    ]
}

ews-resolve-name


This operation verifies aliases and matches display names to the correct mailbox user. It handles one ambiguous name at a time. If there are multiple potential matches, all will be returned, but limited to a maximum of 100 candidates.

Base Command

ews-resolve-name

Input

Argument Name Description Required
identifier The text value of this argument is used to resolve names against the following fields: First name, Last name, Display name, Full name, Office, Alias, SMTP address. Eg. John Doe or sip:johndoe@example.com. Required
full-contact-data Describes whether the full contact details for public contacts for a resolved name are returned. Possible values are: True, False. Optional

Context Output

Path Type Description
EWS.ResolvedNames.FullContactInfo.contactSource String Whether the contact is located in the Exchange store or Active Directory Domain Services (AD DS).
EWS.ResolvedNames.FullContactInfo.culture String Represents the culture for a given item in a mailbox.
EWS.ResolvedNames.FullContactInfo.displayName String The display name of a contact.
EWS.ResolvedNames.FullContactInfo.ItemId String Contains the unique identifier and change key of an item in the Exchange store.
EWS.ResolvedNames.FullContactInfo.emailAddresses String Represents a collection of email addresses for a contact.
EWS.ResolvedNames.FullContactInfo.givenName String Contains a contact’s given name.
EWS.ResolvedNames.FullContactInfo.importance String Describes the importance of an item.
EWS.ResolvedNames.FullContactInfo.initials String Represents the initials of a contact.
EWS.ResolvedNames.FullContactInfo.phoneNumbers.label String The following are the possible values for this attribute: AssistantPhone, BusinessFax, BusinessPhone, BusinessPhone2, Callback, CarPhone, CompanyMainPhone, HomeFax, HomePhone, HomePhone2, Isdn, MobilePhone, OtherFax, OtherTelephone, Pager, PrimaryPhone, RadioPhone, Telex, TtyTddPhone
EWS.ResolvedNames.FullContactInfo.phoneNumbers.phoneNumber String The phone number of the contact
EWS.ResolvedNames.FullContactInfo.physicalAddresses.city String The physical addresses city associated with the contact.
EWS.ResolvedNames.FullContactInfo.physicalAddresses.country String The physical addresses country associated with the contact.
EWS.ResolvedNames.FullContactInfo.physicalAddresses.label String The physical addresses label associated with the contact.
EWS.ResolvedNames.FullContactInfo.physicalAddresses.state String The physical addresses state associated with the contact.
EWS.ResolvedNames.FullContactInfo.physicalAddresses.street String The physical addresses street associated with the contact.
EWS.ResolvedNames.FullContactInfo.physicalAddresses.zipcode String The physical addresses zipcode associated with the contact.
EWS.ResolvedNames.FullContactInfo.postalAddressIndex String Represents the display types for physical addresses.
EWS.ResolvedNames.FullContactInfo.sensitivity String Indicates the sensitivity level of an item.
EWS.ResolvedNames.email_address String The primary SMTP address of a mailbox user.
EWS.ResolvedNames.mailbox_type String The type of mailbox that is represented by the email address.
EWS.ResolvedNames.name String The name of a mailbox user.
EWS.ResolvedNames.routing_type String The address type for the mailbox

Command example

!ews-resolve-name identifier=`example@example.com` full-contact-data=True

Context Example

{
    "EWS": {
        "ResolvedNames": {
            "FullContactInfo": {
                "contactSource": "ActiveDirectory",
                "culture": "en-US",
                "displayName": "ews-2016-test EW2016.",
                "emailAddresses": [
                    "example-sec@example.com",
                    "example@example.com"
                ],
                "givenName": "ews-2016-test",
                "importance": "Normal",
                "initials": "EW2016",
                "phoneNumbers": [
                    {
                        "label": "AssistantPhone",
                        "phoneNumber": null
                    },
                    {
                        "label": "BusinessFax",
                        "phoneNumber": null
                    },
                    {
                        "label": "BusinessPhone",
                        "phoneNumber": null
                    },
                    {
                        "label": "HomePhone",
                        "phoneNumber": null
                    },
                    {
                        "label": "MobilePhone",
                        "phoneNumber": null
                    },
                    {
                        "label": "Pager",
                        "phoneNumber": null
                    }
                ],
                "physicalAddresses": [
                    {
                        "city": null,
                        "country": null,
                        "label": "Business",
                        "state": null,
                        "street": null,
                        "zipcode": null
                    }
                ],
                "postalAddressIndex": "None",
                "sensitivity": "Normal"
            },
            "email_address": "ews-2016-test@lab-demisto.com",
            "mailbox_type": "Mailbox",
            "name": "ews-2016-test EW2016.",
            "routing_type": "SMTP"
        }
    }
}

Human Readable Output

Resolved Names

primary_email_address name mailbox_type routing_type
ews-2016-test@lab-demisto.com ews-2016-test EW2016. Mailbox SMTP

ews-get-out-of-office


Retrieves the out-of-office status for a specified mailbox.

Base Command

ews-get-out-of-office

Input

Argument Name Description Required
target-mailbox The mailbox for which to get the out-of-office status. Required

Context Output

Path Type Description
Account.Email.OutOfOffice.state Unknown Out-of-office state. Result can be: Enabled, Scheduled, Disabled.
Account.Email.OutOfOffice.externalAudience Unknown Out-of-office external audience. Can be “None”, “Known”, or “All”.
Account.Email.OutOfOffice.start Unknown Out-of-office start date.
Account.Email.OutOfOffice.end Unknown Out-of-office end date.
Account.Email.OutOfOffice.internalReply Unknown Out-of-office internal reply.
Account.Email.OutOfOffice.externalReply Unknown Out-of-office external reply.
Account.Email.OutOfOffice.mailbox Unknown Out-of-office mailbox.

Command Example

!ews-get-out-of-office target-mailbox=test@demistodev.onmicrosoft.com

Human Readable Output

end externalAudienc mailbox start state
2019-08-12T13:00:00Z all test@demistodev.onmicrosoft.com 2019-08-11T13:00:00Z Disabled

Context Example

{
    "Account": {
        "Email": {
            "OutOfOffice": {
                "start": "2019-08-11T13:00:00Z", 
                "state": "Disabled", 
                "mailbox": "test@demistodev.onmicrosoft.com", 
                "end": "2019-08-12T13:00:00Z", 
                "externalAudience": "All"
            }
        }
    }
}

ews-recover-messages


Recovers messages that were soft-deleted.

Base Command

ews-recover-messages

Input

Argument Name Description Required
message-ids A CSV list of message IDs. Run the py-ews-delete-items command to retrieve the message IDs. Required
target-folder-path The folder path to recover the messages to. Default is Inbox. Required
target-mailbox The mailbox in which the messages found. If empty, will use the default mailbox. If you specify a different mailbox, you might need impersonation rights to the mailbox. Optional
is-public Whether the target folder is a Public Folder. Possible values are: True, False. Optional

Context Output

Path Type Description
EWS.Items.itemId Unknown The item ID of the recovered item.
EWS.Items.messageId Unknown The message ID of the recovered item.
EWS.Items.action Unknown The action taken on the item. The value will be ‘recovered’.

Command Example

!ews-recover-messages message-ids=&lt;DFVDFmvsCSCS.com&gt; target-folder-path=Moving target-mailbox=test@demistodev.onmicrosoft.com

Human Readable Output

action itemId messageId
recovered AAVCSVS1hN2NkLThmZjdmNTZjNTMxNwBGAAAAAAA4kxh+ed33wX3aBwCyyVyFtlsUQZfBJebinpkUAAAa2bUBAACyyVyFtlscfxxd/AAA= DFVDFmvsCSCS.com

Context Example

{
    "EWS": {
        "Items": {
            "action": "recovered", 
            "itemId": "AAVCSVS1hN2NkLThmZjdmNTZjNTMxNwBGAAAAAAA4kxh+ed33wX3aBwCyyVyFtlsUQZfBJebinpkUAAAa2bUBAACyyVyFtlscfxxd/AAA=", 
            "messageId": "&lt;DFVDFmvsCSCS.com&gt;"
        }
    }
}

ews-create-folder


Creates a new folder in a specified mailbox.

Base Command

ews-create-folder

Input

Argument Name Description Required
new-folder-name The name of the new folder. Required
folder-path Path to locate the new folder. Exchange folder ID is also supported. Default is Inbox. Required
target-mailbox The mailbox in which to create the folder. Optional

Context Output

There is no context output for this command.

Command Example

!ews-create-folder folder-path=Inbox new-folder-name="Created Folder" target-mailbox=test@demistodev.onmicrosoft.com

Human Readable Output

Folder Inbox\Created Folder created successfully

ews-mark-item-as-junk


Marks an item as junk. This is commonly used to block an email address. For more information, see the Microsoft documentation: https://msdn.microsoft.com/en-us/library/office/dn481311(v=exchg.150).aspx

Base Command

ews-mark-item-as-junk

Input

Argument Name Description Required
item-id The item ID to mark as junk. Required
move-items Whether to move the item from the original folder to the junk folder. Possible values are: yes, no. Default is yes. Optional
target-mailbox If empty, will use the default mailbox. If you specify a different mailbox, you might need impersonation rights to the mailbox. Optional

Context Output

There is no context output for this command.

Command Example

!ews-mark-item-as-junk item-id=AAMkcSQ0NmFkOhmZjdmNTZjNTMxNwBGAAAAAAA4kxh+ed3JTJPMPXU3wX3aBwCyyVyFtlsUcsBJebinpkUAAAAAAEMASFDkUAAAfxuiSAAA= move-items=yes target-mailbox=test@demistodev.onmicrosoft.com

Human Readable Output

action itemId
marked-as-junk AAMkcSQ0NmFkOhmZjdmNTZjNTMxNwBGAAAAAAA4kxh+ed3JTJPMPXU3wX3aBwCyyVyFtlsUcsBJebinpkUAAAAAAEMASFDkUAAAfxuiSAAA=

Context Example

{
    "EWS": {
        "Items": {
            "action": "marked-as-junk", 
            "itemId": "AAMkcSQ0NmFkOhmZjdmNTZjNTMxNwBGAAAAAAA4kxh+ed3JTJPMPXU3wX3aBwCyyVyFtlsUcsBJebinpkUAAAAAAEMASFDkUAAAfxuiSAAA="
        }
    }
}

ews-find-folders


Retrieves information for folders for a specified mailbox. Only folders with read permissions will be returned. Your visual folders on the mailbox, such as “Inbox”, are under the folder “Top of Information Store”.

Base Command

ews-find-folders

Input

Argument Name Description Required
target-mailbox The mailbox on which to apply the command. Optional
is-public Whether to find Public Folders. Possible values are: True, False. Optional

Context Output

Path Type Description
EWS.Folders.name string Folder name.
EWS.Folders.id string Folder ID.
EWS.Folders.totalCount Unknown Number of items in folder.
EWS.Folders.unreadCount number Number of unread items in folder
EWS.Folders.changeKey number Folder change key.
EWS.Folders.childrenFolderCount number Number of sub-folders.

Command Example

!ews-find-folders target-mailbox=test@demistodev.onmicrosoft.com

Human Readable Output

root
├── AllContacts
├── AllItems
├── Common Views
├── Deferred Action
├── ExchangeSyncData
├── Favorites
├── Freebusy Data
├── Location
├── MailboxAssociations
├── My Contacts
├── MyContactsExtended
├── People I Know
├── PeopleConnect
├── Recoverable Items
│ ├── Calendar Logging
│ ├── Deletions
│ ── Purges
│ └── Versions
├── Reminders
├── Schedule
├── Sharing
├── Shortcuts
├── Spooler Queue
├── System
├── To-Do Search
├── Top of Information Store
│ ├── Calendar
│ ├── Contacts
│ │ ├── GAL Contacts
│ │ ├── Recipient Cache
│ ├── Conversation Action Settings
│ ├── Deleted Items
│ │ └── Create1
│ ├── Drafts
│ ├── Inbox
...

Context Example

{
    "EWS": {
        "Folders": [    
            {
                "unreadCount": 1, 
                "name": "Inbox", 
                "childrenFolderCount": 1, 
                "totalCount": 44, 
                "changeKey": "**********fefsduQi0", 
                "id": "*******VyFtlFDSAFDSFDAAA="
            }
        ]
    }
}

ews-get-items-from-folder


Retrieves items from a specified folder in a mailbox. The items are order by the item created time, most recent is first.

Base Command

ews-get-items-from-folder

Input

Argument Name Description Required
folder-path The folder path from which to get the items. Required
limit Maximum number of items to return. Default is 100. Optional
target-mailbox The mailbox to on which to apply the command. Optional
is-public Whether the folder is a Public Folder. Default is ‘False’. Possible values are: True, False. Optional
get-internal-item If the email item contains another email as an attachment (EML or MSG file), whether to retrieve the EML/MSG file attachment. Can be “yes” or “no”. Default is “no”. Possible values are: yes, no. Default is no. Optional

Context Output

Path Type Description
EWS.Items.itemId string The item ID of the email.
EWS.Items.hasAttachments boolean Whether the email has attachments.
EWS.Items.datetimeReceived date Received time of the email.
EWS.Items.datetimeSent date Sent time of the email.
EWS.Items.headers Unknown Email headers (list).
EWS.Items.sender string Sender mail address of the email.
EWS.Items.subject string Subject of the email.
EWS.Items.textBody string Body of the email (as text).
EWS.Items.size number Email size.
EWS.Items.toRecipients Unknown Email recipients addresses (list).
EWS.Items.receivedBy Unknown Received by address of the email.
EWS.Items.messageId string Email message ID.
EWS.Items.body string Body of the email (as HTML).
EWS.Items.FileAttachments.attachmentId unknown Attachment ID of file attachment.
EWS.Items.ItemAttachments.attachmentId unknown Attachment ID of the item attachment.
EWS.Items.FileAttachments.attachmentName unknown Attachment name of the file attachment.
EWS.Items.ItemAttachments.attachmentName unknown Attachment name of the item attachment.
EWS.Items.isRead String The read status of the email.
EWS.Items.categories String Categories of the email.

Command Example

!ews-get-items-from-folder folder-path=Test target-mailbox=test@demistodev.onmicrosoft.com limit=1

Human Readable Output

sender subject hasAttachments datetimeReceived receivedBy author toRecipients itemId
test2@demistodev.onmicrosoft.com Get Attachment Email true 2019-08-11T10:57:37Z test@demistodev.onmicrosoft.com test2@demistodev.onmicrosoft.com test@demistodev.onmicrosoft.com AAFSFSFFtlsUQZfBJebinpkUAAABjKMGAACyyVyFtlsUQZfBJebinpkUAAAsfw+jAAA=

Context Example

{
    "EWS": {
        "Items": {
            "body": "&lt;html&gt;\r\n&lt;head&gt;\r\n&lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"&gt;\r\n&lt;style type=\"text/css\" style=\"display:none;\"&gt;&lt;!-- P {margin-top:0;margin-bottom:0;} --&gt;&lt;/style&gt;\r\n&lt;/head&gt;\r\n&lt;body dir=\"ltr\"&gt;\r\n&lt;div id=\"divtagdefaultwrapper\" style=\"font-size:12pt;color:#000000;font-family:Calibri,Helvetica,sans-serif;\" dir=\"ltr\"&gt;\r\n&lt;p style=\"margin-top:0;margin-bottom:0\"&gt;Some text inside email&lt;/p&gt;\r\n&lt;/div&gt;\r\n&lt;/body&gt;\r\n&lt;/html&gt;\r\n", 
            "itemId": "AAFSFSFFtlsUQZfBJebinpkUAAABjKMGAACyyVyFtlsUQZfBJebinpkUAAAsfw+jAAA=", 
            "toRecipients": [
                "test@demistodev.onmicrosoft.com"
            ], 
            "datetimeCreated": "2019-08-11T10:57:37Z", 
            "datetimeReceived": "2019-08-11T10:57:37Z", 
            "author": "test2@demistodev.onmicrosoft.com", 
            "hasAttachments": true, 
            "size": 21435, 
            "subject": "Get Attachment Email", 
            "FileAttachments": [
                {
                    "attachmentName": "atta1.rtf", 
                    "attachmentSHA256": "cd81097bcvdiojf3407a00308b48039e31a44a1c4fdnfkdknce36e4f", 
                    "attachmentType": "FileAttachment", 
                    "attachmentSize": 535, 
                    "attachmentId": "AAFSFSFFtlsUQZfBJebinpkUAAABjKMGAACyyVyFtlsUQZfBJebinpkUAAAsfw+jAAABEgAQAEyq1TB2nKBLpKUiFUJ5Geg=", 
                    "attachmentIsInline": false, 
                    "attachmentLastModifiedTime": "2019-08-11T11:06:02+00:00", 
                    "attachmentContentLocation": null, 
                    "attachmentContentType": "text/rtf", 
                    "originalItemId": "AAFSFSFFtlsUQZfBJebinpkUAAABjKMGAACyyVyFtlsUQZfBJebinpkUAAAsfw+jAAA=", 
                    "attachmentContentId": null
                }
            ], 
            "headers": [
                {
                    "name": "Subject", 
                    "value": "Get Attachment Email"
                }
                            ], 
            "isRead": true, 
            "messageId": "&lt;message_id&gt;", 
            "receivedBy": "test@demistodev.onmicrosoft.com", 
            "datetimeSent": "2019-08-11T10:57:36Z", 
            "lastModifiedTime": "2019-08-11T11:13:59Z", 
            "mailbox": "test@demistodev.onmicrosoft.com", 
            "importance": "Normal", 
            "textBody": "Some text inside email\r\n", 
            "sender": "test2@demistodev.onmicrosoft.com"
        }
    }
}

ews-get-items


Retrieves items by item ID.

Base Command

ews-get-items

Input

Argument Name Description Required
item-ids A CSV list if item IDs. Required
target-mailbox The mailbox on which to run the command on. Optional

Context Output

Path Type Description
EWS.Items.itemId string The email item ID.
EWS.Items.hasAttachments boolean Whether the email has attachments.
EWS.Items.datetimeReceived date Received time of the email.
EWS.Items.datetimeSent date Sent time of the email.
EWS.Items.headers Unknown Email headers (list).
EWS.Items.sender string Sender mail address of the email.
EWS.Items.subject string Subject of the email.
EWS.Items.textBody string Body of the email (as text).
EWS.Items.size number Email size.
EWS.Items.toRecipients Unknown Email recipients addresses (list).
EWS.Items.receivedBy Unknown Received by address of the email.
EWS.Items.messageId string Email message ID.
EWS.Items.body string Body of the email (as HTML).
EWS.Items.FileAttachments.attachmentId unknown Attachment ID of the file attachment.
EWS.Items.ItemAttachments.attachmentId unknown Attachment ID of the item attachment.
EWS.Items.FileAttachments.attachmentName unknown Attachment name of the file attachment.
EWS.Items.ItemAttachments.attachmentName unknown Attachment name of the item attachment.
EWS.Items.isRead String The read status of the email.
EWS.Items.categories String Categories of the email.
Email.CC String Email addresses CC’ed to the email.
Email.BCC String Email addresses BCC’ed to the email.
Email.To String The recipient of the email.
Email.From String The sender of the email.
Email.Subject String The subject of the email.
Email.Text String The plain-text version of the email.
Email.HTML String The HTML version of the email.
Email.HeadersMap String The headers of the email.

Command Example

!ews-get-items item-ids=AAMkADQ0NmFkODFkLWQ4MDEtNDFDFZjNTMxNwBGAAAAAAA4kxhFFAfxw+jAAA= target-mailbox=test@demistodev.onmicrosoft.com

Human Readable Output

Identical outputs to ews-get-items-from-folder command.

ews-move-item-between-mailboxes


Moves an item from one mailbox to different mailbox.

Base Command

ews-move-item-between-mailboxes

Input

Argument Name Description Required
item-id The item ID to move. Required
destination-folder-path The folder in the destination mailbox to which to move the item. You can specify a complex path, for example, “Inbox\Phishing”. Required
destination-mailbox The mailbox to which to move the item. Required
source-mailbox The mailbox from which to move the item (conventionally called the “target-mailbox”, the target mailbox on which to run the command). Optional
is-public Whether the destination folder is a Public Folder. Default is “False”. Possible values are: True, False. Optional

Context Output

Path Type Description
EWS.Items.movedToMailbox string The mailbox wo which the item was moved.
EWS.Items.movedToFolder string The folder to which the item was moved.
EWS.Items.action string The action taken on the item. The value will be “moved”.

Command Example

!ews-move-item-between-mailboxes item-id=AAMkAGY3OTQyMzMzLWYxNjktNDE0My05NFSFSyNzBkNABGAAAAAACYCKjWAjq/zTrN6vWSzK4OWAAK2ISFSA= destination-folder-path=Moving destination-mailbox=test@demistodev.onmicrosoft.com source-mailbox=test2@demistodev.onmicrosoft.com

Human Readable Output

Item was moved successfully.

Context Example

{
    "EWS": {
        "Items": {
            "movedToMailbox": "test@demistodev.onmicrosoft.com", 
            "movedToFolder": "Moving"
        }
    }
}

ews-get-folder


Retrieves a single folder.

Base Command

ews-get-folder

Input

Argument Name Description Required
target-mailbox The mailbox on which to apply the search. Optional
folder-path The path of the folder to retrieve. If empty, will retrieve the folder “AllItems”. Default is AllItems. Optional
is-public Whether the folder is a Public Folder. Default is “False”. Possible values are: True, False. Optional

Context Output

Path Type Description
EWS.Folders.id string Folder ID.
EWS.Folders.name string Folder name.
EWS.Folders.changeKey string Folder change key.
EWS.Folders.totalCount number Total number of emails in the folder.
EWS.Folders.childrenFolderCount number Number of sub-folders.
EWS.Folders.unreadCount number Number of unread emails in the folder.

Command Example

!ews-get-folder folder-path=demistoEmail target-mailbox=test@demistodev.onmicrosoft.com

Human Readable Output

changeKey childrenFolderCount id name totalCount unreadCount
***yFtCdJSH 0 AAMkADQ0NmFkODFkLWQ4MDEtNDE4Mi1hN2NlsjflsjfSF= demistoEmail 1 0

Context Example

{
    "EWS": {
        "Folders": {
            "unreadCount": 0, 
            "name": "demistoEmail", 
            "childrenFolderCount": 0, 
            "totalCount": 1, 
            "changeKey": "***yFtCdJSH", 
            "id": "AAMkADQ0NmFkODFkLWQ4MDEtNDE4Mi1hN2NlsjflsjfSF="
        }
    }
}

ews-get-autodiscovery-config


Returns the auto-discovery information. Can be used to manually configure the Exchange Server.

Base Command

ews-get-autodiscovery-config

Input

There are no input arguments for this command.

Context Output

There is no context output for this command.

Command Example


#### Human Readable Output

>|api_version|auth_type|build|service_endpoint|
>|---|---|---|---|
>| Exchange2016 |###|--|<https://outlook.office365.com/EWS/Exchange.asmx>|

### ews-expand-group

***
Expands a distribution list to display all members. By default, expands only first layer of the distribution list. If recursive-expansion is "True", the command expands nested distribution lists and returns all members.

#### Base Command

`ews-expand-group`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| email-address | Email address of the group to expand. | Required |
| recursive-expansion | Whether to enable recursive expansion. Default is "False". Possible values are: True, False. Default is False. | Optional |

#### Context Output

There is no context output for this command.

#### Command Example

```!ews-expand-group email-address="TestPublic" recursive-expansion="False"```

#### Human Readable Output

>|displayNam|mailbox|mailboxtype|
>|---|---|---|
>| John Wick|<john@wick.com>|MailBox|

#### Context Example

```json
{
    "EWS.ExpandGroup": {
        "name": "TestPublic", 
        "members": [
            {
                "mailboxType": "Mailbox", 
                "displayName": "John Wick", 
                "mailbox": "john@wick.com"
            }
        ]
    }
}

ews-mark-items-as-read


Marks items as read or unread.

Base Command

ews-mark-items-as-read

Input

Argument Name Description Required
item-ids A CSV list of item IDs. Required
operation How to mark the item. Can be “read” or “unread”. Default is “read”. Possible values are: read, unread. Default is read. Optional
target-mailbox The mailbox on which to run the command. If empty, the command will be applied on the default mailbox. Optional

Context Output

Path Type Description
EWS.Items.action String The action that was performed on item.
EWS.Items.itemId String The ID of the item.
EWS.Items.messageId String The message ID of the item.

Command Example

!ews-mark-items-as-read item-ids=AAMkADQ0NFSffU3wX3aBwCyyVyFtlsUQZfBJebinpkUAAABjKMnpkUAAAfxw+jAAA= operation=read target-mailbox=test@demistodev.onmicrosoft.com

Human Readable Output

action itemId messageId
mark-as-read AAMkADQ0NFSffU3wX3aBwCyyVyFtlsUQZfBJebinpkUAAABjKMnpkUAAAfxw+jAAA= id

Context Example

{
    "EWS": {
        "Items": {
            "action": "marked-as-read", 
            "itemId": "AAMkADQ0NFSffU3wX3aBwCyyVyFtlsUQZfBJebinpkUAAABjKMnpkUAAAfxw+jAAA= ", 
            "messageId": "&lt;message_id&gt;"
        }
    }
}

ews-get-items-as-eml


Retrieves items by item ID and uploads it’s content as eml file.

Base Command

ews-get-items-as-eml

Input

Argument Name Description Required
item-id The item ID of item to upload as and EML file. Required
target-mailbox The mailbox in which this email was found. If empty, the default mailbox is used. Otherwise the user might require impersonation rights to this mailbox. Optional

Context Output

Path Type Description
File.Size String The size of the file.
File.SHA1 String The SHA1 hash of the file.
File.SHA256 String The SHA256 hash of the file.
File.SHA512 String The SHA512 hash of the file.
File.Name String The name of the file.
File.SSDeep String The SSDeep hash of the file.
File.EntryID String EntryID of the file
File.Info String Information about the file.
File.Type String The file type.
File.MD5 String The MD5 hash of the file.
File.Extension String The extension of the file.

send-mail


Sends an email using EWS.

Base Command

send-mail

Input

Argument Name Description Required
to A CSV list of email addresses for the ‘to’ field. Required
cc A CSV list of email addresses for the ‘cc’ field. Optional
bcc A CSV list of email addresses for the ‘bcc’ field. Optional
subject Subject for the email to be sent. Required
replyTo The email address specified in the ‘reply to’ field. Optional
body The contents (body) of the email to send. This argument overrides the “htmlBody” argument if the “bodyType” argument is Text. Optional
htmlBody HTML formatted content (body) of the email to be sent. This argument overrides the “body” argument if the “bodyType” argument is HTML. Optional
bodyType The message response body type. Possible values are: Text, HTML. Default is Text. Optional
attachIDs A CSV list of War Room entry IDs that contain files, and are used to attach files to the outgoing email. For example: attachIDs=15@8,19@8. Optional
attachNames A CSV list of names of attachments to send. Should be the same number of elements as attachIDs. Optional
attachCIDs A CSV list of CIDs to embed attachments within the email itself. Optional
raw_message Raw email message from MimeContent type. Optional
from The email address from which to send mail. Optional
handle_inline_image Whether to handle inline images in the HTML body. When set to ‘True’, inline images will be extracted from the HTML and attached to the email as an inline attachment object. Note that in some cases, attaching the image as an object may cause the image to disappear when replying to the email. Additionally, sending the image in the html body as base64 data (inline image) may cause the image to disappear if the image is too large or recognized as malicious and subsequently deleted. Possible values are: True, False. Default is True. Optional

Context Output

There is no context output for this command.

reply-mail


Replies to an email using EWS.

Command Example

!send-mail body="hello this is a test" subject=Hi to=avishai@demistodev.onmicrosoft.com

Human Readable Output

Sent email

attachments from subject to
  avishai@demistodev.onmicrosoft.com Hi avishai@demistodev.onmicrosoft.com

Base Command

reply-mail

Input

Argument Name Description Required
inReplyTo ID of the item to reply to. Required
to A CSV list of email addresses for the ‘to’ field. Required
cc A CSV list of email addresses for the ‘cc’ field. Optional
bcc A CSV list of email addresses for the ‘bcc’ field. Optional
subject Subject for the email to be sent. Optional
body The contents (body) of the email to be sent. Optional
htmlBody HTML formatted content (body) of the email to be sent. This argument overrides the “body” argument. Optional
attachIDs A CSV list of War Room entry IDs that contain files, and are used to attach files to the outgoing email. For example: attachIDs=15@8,19@8. Optional
attachNames A CSV list of names of attachments to send. Should be the same number of elements as attachIDs. Optional
attachCIDs A CSV list of CIDs to embed attachments within the email itself. Optional
handle_inline_image Whether to handle inline images in the HTML body. When set to ‘True’, inline images are extracted from the HTML and attached to the email as inline attachment objects. Possible values are: True, False. Default is True. NOTE: Sometimes inline images sent in emails may not appear for recipients, either because their email system blocks the image (for example, due to image size or the email is flagged as malicious) or for other reasons. Optional

Context Output

There is no context output for this command.

Command Example

!reply-mail item_id=AAMkAGY3OTQyMzMzLWYxNjktNDE0My05NmZhLWQ5MGY1YjIyNzBkNABGAAAAAACYCKjWAnXBTrnhgWJCcLX7BwDrxRwRjq/zTrN6vWSzK4OWAAAAAAEMAADrxRwRjq/zTrN6vWSzK4OWAAPYQGFeAAA= body=hello subject=hi to="avishai@demistodev.onmicrosoft.com"

Human Readable Output

Sent email

attachments from subject to
  avishai@demistodev.onmicrosoft.com hi avishai@demistodev.onmicrosoft.com

Additional Information

EWS Permissions

To perform actions on mailboxes of other users, and to execute searches on the Exchange server, you need specific permissions. For a comparison between Delegate and Impersonation permissions, see the Microsoft documentation

Permission Use Case How to Configure
Delegated One-to-one relationship between users. Read more here.
Impersonation A single account needs to access multiple mailboxes. Read more here.
eDiscovery A single account needs to access multiple mailboxes. Read more here.
Compliance Search Perform searches across mailboxes and get an estimate of the results. Read more here.

New-Compliance Search

The EWS v2 integration uses remote ps-session to run commands of compliance search as part of Office 365. To check if your account can connect to Office 365 Security & Compliance Center via powershell, check the following steps. New-Compliance search is a long-running task which has no limitation of searched mailboxes and therefore the suggestion is to useOffice 365 Search and Deleteplaybook. New-Compliance search returns statistics of matched content search query and doesn’t return preview of found emails in contrast toews-search-mailboxescommand.

Troubleshooting

For troubleshooting information, see the EWS V2 Troubleshooting.

Configuration parameters

  • credentials — Email address (required)
  • defaultTargetMailbox — Email address from which to fetch incidents (required)
  • folder — Name of the folder from which to fetch incidents (supports Exchange Folder ID and sub-folders e.g. Inbox/Phishing)
  • isPublicFolder — Public Folder
  • impersonation — Has impersonation rights
  • proxy — Use system proxy settings
  • isFetch — Fetch incidents
  • fetch_time — First fetch timestamp (<number> <time unit>, e.g., 12 hours, 7 days)
  • markAsRead — Mark fetched emails as read
  • incidentType — Incident type
  • incidentFetchInterval — Incidents Fetch Interval
  • ewsServer — ┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉ ‎ Manual Mode Exchange Server Hostname or IP address
  • domainAndUserman — DOMAIN\USERNAME (e.g. DEMISTO.INT\admin)
  • defaultServerVersion — Exchange Server Version (On-Premise only. Supported versions: 2007, 2010, 2010_SP2, 2013, 2013_SP1, 2016, and 2019)
  • insecure — Trust any certificate (not secure)
  • authType — ┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉ ‎ Advanced Mode Override Authentication Type (NTLM, Basic, or Digest).
  • requestTimeout — Timeout (in seconds) for HTTP requests to Exchange Server
  • maxFetch — Max incidents per fetch
  • separate_process — Run as a separate process (protects against memory depletion)
  • legacy_name — Use legacy attachment name
  • skip_unparsable_emails — Skip unparsable emails during fetch incidents

Commands (24)

  • ews-create-folder

    Creates a new folder in a specified mailbox.

  • ews-delete-attachment

    Deletes the attachments of an item (email message).

  • ews-delete-items

    Delete items from mailbox. This command requires eDiscovery permissions to the Exchange Server. For more information, see the EWSv2 integration documentation.

  • ews-expand-group

    Expands a distribution list to display all members. By default, expands only first layer of the distribution list. If recursive-expansion is "True", the command expands nested distribution lists and returns all members.

  • ews-find-folders

    Retrieves information for folders for a specified mailbox. Only folders with read permissions will be returned. Your visual folders on the mailbox, such as "Inbox", are under the folder "Top of Information Store".

  • ews-get-attachment

    Retrieves the actual attachments from an item (email message). To get all attachments for a message, only specify the item-id argument.

  • ews-get-autodiscovery-config

    Returns the auto-discovery information. Can be used to manually configure the Exchange Server.

  • ews-get-contacts

    Retrieves contacts for a specified mailbox.

  • ews-get-folder

    Retrieves a single folder.

  • ews-get-items

    Retrieves items by item ID.

  • ews-get-items-as-eml

    Retrieves items by item ID and uploads it's content as eml file.

  • ews-get-items-from-folder

    Retrieves items from a specified folder in a mailbox. The items are order by the item created time, most recent is first.

  • ews-get-out-of-office

    Retrieves the out-of-office status for a specified mailbox.

  • ews-get-searchable-mailboxes

    Returns a list of searchable mailboxes. This command requires eDiscovery permissions to the Exchange Server. For more information, see the EWSv2 integration documentation.

  • ews-mark-item-as-junk

    Marks an item as junk. This is commonly used to block an email address. For more information, see the Microsoft documentation: https://msdn.microsoft.com/en-us/library/office/dn481311(v=exchg.150).aspx.

  • ews-mark-items-as-read

    Marks items as read or unread.

  • ews-move-item

    Move an item to different folder in the mailbox.

  • ews-move-item-between-mailboxes

    Moves an item from one mailbox to different mailbox.

  • ews-recover-messages

    Recovers messages that were soft-deleted.

  • ews-resolve-name

    This operation verifies aliases and matches display names to the correct mailbox user. It handles one ambiguous name at a time. If there are multiple potential matches, all will be returned, but limited to a maximum of 100 candidates.

  • ews-search-mailbox

    Searches for items in the specified mailbox. Specific permissions are needed for this operation to search in a target mailbox other than the default.

  • ews-search-mailboxes

    Searches over multiple mailboxes or all Exchange mailboxes. Use either the mailbox-search-scope command or the email-addresses command to search specific mailboxes. This command requires eDiscovery permissions to the Exchange Server. For more information, see the EWS v2 integration documentation.

  • reply-mail

    Replies to an email using EWS.

  • send-mail

    Sends an email using EWS.

import datetime
import json
import logging
import uuid

import dateparser
import demistomock as demisto
import EWSv2
import pytest
from EWSApiModule import EWSClient
from EWSv2 import (
    fetch_last_emails,
    get_attachment_name,
    get_message_for_body_type,
    parse_item_as_dict,
    parse_physical_address,
    get_formatted_message,
)
from exchangelib import Body, Contact, EWSDate, EWSDateTime, EWSTimeZone, HTMLBody, Mailbox, Message
from exchangelib.errors import ErrorInvalidIdMalformed, ErrorItemNotFound, ErrorNameResolutionNoResults, UnauthorizedError
from exchangelib.indexed_properties import PhoneNumber, PhysicalAddress
from exchangelib.items import Item
from exchangelib.properties import ItemId
from pytest_mock import MockerFixture


class TestNormalCommands:
    """ """

    class MockClient(EWSClient):
        class MockAccount:
            DEFAULT_FOLDER_TRAVERSAL_DEPTH = 3

            def __init__(self):
                self.root = self
                self.walk_res = []
                self.all_res = ""
                self.contacts = self

            def walk(self):
                return self.walk_res

            def tree(self):
                return ""

            def all(self):
                return self.all_res

        def __init__(self, max_fetch: int = 50):
            self.default_target_mailbox = ""
            self.client_id = ""
            self.client_secret = ""
            self.tenant_id = ""
            self.account_email = ""
            self.folder = ""
            self.is_public_folder = False
            self.request_timeout = ""
            self.max_fetch = max_fetch
            self.self_deployed = False
            self.insecure = False
            self.proxy = False
            self.account = self.MockAccount()
            self.protocol = ""
            self.mark_as_read = False
            self.folder_name = "Inbox"

        def get_account(self, target_mailbox=None, access_type=None):
            return self.account

        def get_protocol(self):
            return self.protocol

        def get_attachments_for_item(self, item_id, account, attachment_ids=None):
            return ""

        def is_default_folder(self, folder_path, is_public):
            return ""

        def get_folder_by_path(self, path, account=None, is_public=False):
            return ""

        def send_email(self, message):
            return

        def reply_email(self, inReplyTo, to, body, subject, bcc, cc, htmlBody, attachments, from_mailbox, account):
            return ""


def test_keys_to_camel_case():
    assert EWSv2.keys_to_camel_case("this_is_a_test") == "thisIsATest"
    # assert keys_to_camel_case(('this_is_a_test', 'another_one')) == ('thisIsATest', 'anotherOne')
    obj = {}
    obj["this_is_a_value"] = "the_value"
    obj["this_is_a_list"] = []
    obj["this_is_a_list"].append("list_value")
    res = EWSv2.keys_to_camel_case(obj)
    assert res["thisIsAValue"] == "the_value"
    assert res["thisIsAList"][0] == "listValue"


def test_start_logging(mocker):
    mocker.patch.object(EWSv2, "is_debug_mode", return_value=True)
    EWSv2.log_stream = None
    EWSv2.log_handler = None
    EWSv2.start_logging()
    logging.getLogger().debug("test this")
    assert "test this" in EWSv2.log_stream.getvalue()


@pytest.mark.parametrize("since_datetime, expected_result", [("", EWSDateTime.from_string("2021-05-23 13:18:14.901293+00:00"))])
def test_fetch_last_emails_first_fetch(mocker, since_datetime, expected_result):
    """
    Given:
        - First fetch timestamp - no last_run
    When:
        - Fetching last emails

    Then:
        - Verify datetime_received__gte is ten minutes earlier
    """

    class MockObject:
        def filter(self, datetime_received__gte=""):
            return MockObject2()

    class MockObject2:
        def filter(self):
            return MockObject2()

        def only(self, *args):
            return self

        def order_by(self, *args):
            return [Message(), Message(), Message(), Message(), Message()]

    client = TestNormalCommands.MockClient()
    mocker.patch.object(dateparser, "parse", return_value=datetime.datetime(2021, 5, 23, 13, 18, 14, 901293, datetime.UTC))
    mocker.patch.object(TestNormalCommands.MockClient, "get_folder_by_path", return_value=MockObject())
    mocker.patch.object(MockObject, "filter")

    fetch_last_emails(client, since_datetime=since_datetime)
    assert MockObject.filter.call_args[1].get("datetime_received__gte") == expected_result


@pytest.mark.parametrize(
    "since_datetime, expected_result", [("2021-05-23 21:18:14.901293+00:00", "2021-05-23 21:18:14.901293+00:00")]
)
def test_fetch_last_emails_last_run(mocker, since_datetime, expected_result):
    """
    Given:
        - Not the first time fetching - last_run with a date
    When:
        - Fetching last emails

    Then:
        - Verify datetime_received__gte according to the datetime received
    """

    class MockObject:
        def filter(self, datetime_received__gte=""):
            return MockObject2()

    class MockObject2:
        def filter(self):
            return MockObject2()

        def only(self, *args):
            return self

        def order_by(self, *args):
            return [Message(), Message(), Message(), Message(), Message()]

    mocker.patch.object(TestNormalCommands.MockClient, "get_folder_by_path", return_value=MockObject())
    mocker.patch.object(MockObject, "filter")

    client = TestNormalCommands.MockClient()

    fetch_last_emails(client, since_datetime=since_datetime)
    assert MockObject.filter.call_args[1].get("datetime_received__gte") == expected_result


@pytest.mark.parametrize("limit, expected_result", [(6, 5), (2, 2), (5, 5)])
def test_fetch_last_emails_limit(mocker, limit, expected_result):
    """
    Given:
        - Max fetch is 6
        - Max fetch is 2
        - Max fetch is 5

    When:
        - Fetching last emails - need to make sure to return emails according to the max_fetch param.

    Then:
        - Return 5 emails (Cause we only have 5 emails)
        - Return 2 emails
        - Return 5 emails
    """

    class MockObject:
        def filter(self, datetime_received__gte=""):
            return MockObject2()

    class MockObject2:
        def filter(self):
            return MockObject2()

        def only(self, *args):
            return self

        def order_by(self, *args):
            return [Message(), Message(), Message(), Message(), Message()]

    mocker.patch.object(TestNormalCommands.MockClient, "get_folder_by_path", return_value=MockObject())
    client = TestNormalCommands.MockClient(max_fetch=limit)

    x = fetch_last_emails(client, since_datetime="since_datetime")
    assert len(x) == expected_result


def test_get_formatted_message_bad_header():
    """
    Given a message that has a bad header
    When: Calling get_formatted_message
    Then: There should be no exceptions
    """
    import email

    msg = email.message.Message()
    msg["From"] = "hello@example.com"
    msg["To"] = "world@example.com"
    msg["Subject"] = "Test Email - subject"

    # Set a random body
    body = "This is a randomly generated message body"
    msg.set_payload(body)
    msg.add_header("Foo", "From: value==value=<= .palo.com =?utf-8?q?=3E?=")
    msg.add_header("Foo", "From: \tvalue=\r\n =value=\t<\r\n= .palo.com\r\n =?utf-8?q?=3E?=\r\n")

    formatted_message = get_formatted_message(msg)
    assert type(formatted_message) is bytes
    assert body in str(formatted_message)


def test_get_formatted_message_good_header():
    """
    Given a message that has a good header
    When: Calling get_formatted_message
    Then: The mail should be parsed properly
    """
    import email.message

    msg = email.message.Message()
    msg["From"] = "hello@example.com"
    msg["To"] = "world@example.com"
    msg["Subject"] = "Test Email - subject"

    # Set a random body
    body = "This is a randomly generated message body"
    msg.set_payload(body)
    msg.add_header("Foo", "From: value==value=<= .palo.com =?utf-8?q?=3E?=")
    assert (
        get_formatted_message(msg) == "From: hello@example.com\nTo: world@example.com\nSubject: Test Email - subject\nFoo: "
        "From: value==value=<= .palo.com =?utf-8?q?=3E?=\n\nThis is a randomly generated message body"
    )


def test_fetch_last_emails_fail(mocker):
    """
    This UT is added due to the following issue: XSUP-28730
    where an ErrorMimeContentConversionFailed exception is raised if there was a corrupt object in the stream of
    results returned from the fetch process (exchangelib module behavior).
    If such exception is encountered, it would be handled internally so that the integration would not crash.

    Given:
        - First exception raised is ErrorMimeContentConversionFailed
        - Second exception raised is ValueError

    When:
        - Iterating over mail objects when fetching last emails

    Then:
        - Catch ErrorMimeContentConversionFailed, print relevant debug message
          for encountered corrupt object and continue iteration to next object
        - Catch ValueError, and raise it forward
    """
    from EWSv2 import ErrorMimeContentConversionFailed

    class MockObject:
        def filter(self, datetime_received__gte=""):
            return MockObject2()

    class MockObject2:
        def filter(self):
            return MockObject2()

        def only(self, *args):
            return self

        def order_by(self, *args):
            return [Message(), Message(), Message(), Message(), Message()]

    mocker.patch.object(TestNormalCommands.MockClient, "get_folder_by_path", return_value=MockObject())
    client = TestNormalCommands.MockClient(max_fetch=1)

    mocker.patch("EWSv2.isinstance", side_effect=[ErrorMimeContentConversionFailed(AttributeError()), ValueError()])

    with pytest.raises(ValueError) as e:
        fetch_last_emails(client, since_datetime="since_datetime")
        assert str(e) == "Got an error when pulling incidents. You might be using the wrong exchange version."


def test_fetch_last_emails_object_stream_behavior(mocker):
    """
    This UT is added due to the following issue: XSUP-28730
    where an ErrorMimeContentConversionFailed exception is raised if there was a corrupt object in the stream of
    results returned from the fetch process (exchangelib module behavior).
    If such exception is encountered, it would be handled internally so that the integration would not crash

    Given:
        - A stream of 3 fetched objects, where objects in indexes 0,2 are valid message objects
          and the object in index 1 is an exception object (corrupt object)

    When:
        - Iterating over mail objects when fetching last emails

    Then:
        - Iterate over the fetched objects
        - Catch the corrupt object object, print relevant debug message
          and continue iteration to next object
        - Assert only valid objects are in the result
    """
    from EWSv2 import ErrorMimeContentConversionFailed

    class MockObject:
        def filter(self, datetime_received__gte=""):
            return MockObject2()

    class MockObject2:
        def filter(self):
            return MockObject2()

        def only(self, *args):
            return self

        def order_by(self, *args):
            return [Message(), Message(), Message()]

    mocker.patch.object(TestNormalCommands.MockClient, "get_folder_by_path", return_value=MockObject())
    client = TestNormalCommands.MockClient(max_fetch=3)

    mocker.patch("EWSv2.isinstance", side_effect=[True, ErrorMimeContentConversionFailed(AttributeError()), True])

    x = fetch_last_emails(client, since_datetime="since_datetime")
    assert len(x) == 2


def test_dateparser():
    """Test that dateparser works fine. See: https://github.com/demisto/etc/issues/39240"""
    now = datetime.datetime.now()
    res = dateparser.parse("10 minutes")
    assert res is not None
    assert res < now


MESSAGES = [
    Message(
        subject="message1",
        message_id="message1",
        text_body="Hello World",
        body="message1",
        datetime_received=EWSDateTime(2021, 7, 14, 13, 00, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_sent=EWSDateTime(2021, 7, 14, 13, 00, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_created=EWSDateTime(2021, 7, 14, 13, 00, 00, tzinfo=EWSTimeZone("UTC")),
    ),
    Message(
        subject="message2",
        message_id="message2",
        text_body="Hello World",
        body="message2",
        datetime_received=EWSDateTime(2021, 7, 14, 13, 9, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_sent=EWSDateTime(2021, 7, 14, 13, 9, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_created=EWSDateTime(2021, 7, 14, 13, 9, 00, tzinfo=EWSTimeZone("UTC")),
    ),
    Message(
        subject="message3",
        message_id="message3",
        text_body="Hello World",
        body="message3",
        datetime_received=EWSDateTime(2021, 7, 14, 13, 9, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_sent=EWSDateTime(2021, 7, 14, 13, 9, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_created=EWSDateTime(2021, 7, 14, 13, 9, 00, tzinfo=EWSTimeZone("UTC")),
    ),
    Message(
        subject="message4",
        message_id="message4",
        text_body="Hello World",
        body="message4",
        datetime_received=EWSDateTime(2021, 7, 14, 13, 10, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_sent=EWSDateTime(2021, 7, 14, 13, 9, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_created=EWSDateTime(2021, 7, 14, 13, 11, 00, tzinfo=EWSTimeZone("UTC")),
    ),
]
CASE_FIRST_RUN_NO_INCIDENT: tuple = ({}, [], {"lastRunTime": None, "folderName": "Inbox", "ids": [], "errorCounter": 0})
CASE_FIRST_RUN_FOUND_INCIDENT: tuple = (
    {},
    MESSAGES[:1],
    {"lastRunTime": "2021-07-14T13:00:00Z", "folderName": "Inbox", "ids": ["message1"], "errorCounter": 0},
)
CASE_SECOND_RUN_FOUND_ONE_INCIDENT = (
    {"lastRunTime": "2021-07-14T12:59:17Z", "folderName": "Inbox", "ids": []},
    MESSAGES[:1],
    {"lastRunTime": "2021-07-14T13:00:00Z", "folderName": "Inbox", "ids": ["message1"], "errorCounter": 0},
)
CASE_SECOND_RUN_FOUND_MORE_THAN_ONE_FIRST_RUN = (
    {"lastRunTime": "2021-07-14T13:05:17Z", "folderName": "Inbox", "ids": ["message1"]},
    MESSAGES[0:3],
    {"lastRunTime": "2021-07-14T13:09:00Z", "folderName": "Inbox", "ids": ["message2"], "errorCounter": 0},
)
CASE_SECOND_RUN_FOUND_MORE_THAN_ONE_NEXT_RUN = (
    {"lastRunTime": "2021-07-14T13:09:00Z", "folderName": "Inbox", "ids": ["message2"]},
    MESSAGES[1:3],
    {"lastRunTime": "2021-07-14T13:09:00Z", "folderName": "Inbox", "ids": ["message2", "message3"], "errorCounter": 0},
)
CASE_SECOND_RUN_NO_INCIDENTS: tuple = (
    {"lastRunTime": "2021-07-14T12:59:17Z", "folderName": "Inbox", "ids": ["message1"]},
    [],
    {"lastRunTime": "2021-07-14T12:59:17Z", "folderName": "Inbox", "ids": ["message1"], "errorCounter": 0},
)
CASE_SECOND_RUN_DIFFERENT_CREATED_RECEIVED_TIME = (
    {"lastRunTime": "2021-07-14T13:09:00Z", "folderName": "Inbox", "ids": []},
    MESSAGES[3:],
    {"lastRunTime": "2021-07-14T13:10:00Z", "folderName": "Inbox", "ids": ["message4"], "errorCounter": 0},
)
CASES = [
    CASE_FIRST_RUN_NO_INCIDENT,
    CASE_FIRST_RUN_FOUND_INCIDENT,
    CASE_SECOND_RUN_FOUND_ONE_INCIDENT,
    CASE_SECOND_RUN_FOUND_MORE_THAN_ONE_FIRST_RUN,
    CASE_SECOND_RUN_FOUND_MORE_THAN_ONE_NEXT_RUN,
    CASE_SECOND_RUN_NO_INCIDENTS,
    CASE_SECOND_RUN_DIFFERENT_CREATED_RECEIVED_TIME,
]


@pytest.mark.parametrize("current_last_run, messages, expected_last_run", CASES)
def test_last_run(mocker, current_last_run, messages, expected_last_run):
    """Check the fetch command.

    Given:
        - Last Run data including time and ids to be excluded.
    When:
        - Running fetch command.
    Then:
        - Validates the new Last Run new excluded IDs and last run time.
    """
    import demistomock as demisto
    from EWSv2 import fetch_emails_as_incidents

    class MockObject:
        def filter(self, datetime_received__gte=""):
            return MockObject2()

    class MockObject2:
        def filter(self):
            return MockObject2()

        def only(self, *args):
            return self

        def order_by(self, *args):
            return messages

    client = TestNormalCommands.MockClient(max_fetch=1)
    mocker.patch.object(TestNormalCommands.MockClient, "get_folder_by_path", return_value=MockObject())
    last_run = mocker.patch.object(demisto, "setLastRun")
    mocker.patch.object(demisto, "getLastRun", return_value=current_last_run)
    fetch_emails_as_incidents(client, False)
    assert last_run.call_args[0][0].get("lastRunTime") == expected_last_run.get("lastRunTime")
    assert set(last_run.call_args[0][0].get("ids")) == set(expected_last_run.get("ids"))


@pytest.mark.parametrize(
    "skip_unparsable_emails_param, exception_type, expected",
    [
        (True, IndexError("Unparsable email ignored"), "Unparsable email ignored"),
        (True, UnicodeError("Unparsable email ignored"), "Unparsable email ignored"),
        (True, Exception("Unparsable email not ignored"), "Unparsable email not ignored"),
        (False, Exception("Unparsable email not ignored"), "Unparsable email not ignored"),
        (False, IndexError("Unparsable email not ignored"), "Unparsable email not ignored"),
    ],
)
def test_skip_unparsable_emails(mocker, skip_unparsable_emails_param, exception_type, expected):
    """Check the fetch command in skip_unparsable_emails parameter use-cases.

    Given:
        - An exception has occurred while processing an email message.
    When:
        - Running fetch command.
    Then:
        - If skip_unparsable_emails parameter is True, and the Exception is a specific type we allow to fail due to parsing error:
            log the exception message and continue processing the next email (ignore unparsable email).
        - If skip_unparsable_emails parameter is False, raise the exception (crash the fetch command).
    """
    import demistomock as demisto
    from EWSv2 import fetch_emails_as_incidents

    class MockEmailObject:
        def __init__(self):
            self.message_id = "Value"

    client = TestNormalCommands.MockClient()
    mocker.patch.object(
        demisto, "getLastRun", return_value={"lastRunTime": "2021-07-14T12:59:17Z", "folderName": "Inbox", "ids": []}
    )
    mocker.patch.object(EWSv2, "parse_incident_from_item", side_effect=exception_type)
    mocker.patch.object(EWSv2, "fetch_last_emails", return_value=[MockEmailObject()])
    with pytest.raises((Exception, UnicodeError, IndexError)) as e:
        fetch_emails_as_incidents(client, skip_unparsable_emails_param)
        assert expected == str(e)


class MockItem:
    def __init__(self, item_id):
        self.id = item_id


class MockAccount:
    def __init__(self, primary_smtp_address="", error=401):
        self.primary_smtp_address = primary_smtp_address
        self.error = error

    @property
    def root(self):
        if self.error == 401:
            raise UnauthorizedError("Wrong username or password")
        if self.error == 404:
            raise Exception("Page not found")

    def fetch(self, ids):
        if isinstance(ids, type(map)):
            ids = list(ids)

        result = []

        for item in ids:
            item_id = item.id
            if item_id == "3":
                result.append(ErrorInvalidIdMalformed(value="malformed ID 3"))
            elif item_id == "4":
                result.append(ErrorItemNotFound(value="ID 4 was not found"))
            else:
                result.append(item_id)
        return result


def test_send_mail(mocker):
    """
    Given -
        to, subject and replyTo arguments to send an email.

    When -
        trying to send an email

    Then -
        verify the context output is returned correctly and that the 'to' and 'replyTo' arguments were sent
        as a list of strings.
    """
    from EWSv2 import send_email

    mocker.patch.object(
        TestNormalCommands.MockClient, "get_account", return_value=MockAccount(primary_smtp_address="test@gmail.com")
    )
    send_email_mocker = mocker.patch.object(EWSv2, "send_email_to_mailbox", return_value=(""))

    client = TestNormalCommands.MockClient()
    results = send_email(client, {"to": "test@gmail.com", "subject": "test", "replyTo": "test1@gmail.com"})
    assert send_email_mocker.call_args.kwargs.get("to") == ["test@gmail.com"]
    assert send_email_mocker.call_args.kwargs.get("reply_to") == ["test1@gmail.com"]
    assert results[0].get("Contents") == {
        "from": "test@gmail.com",
        "to": ["test@gmail.com"],
        "subject": "test",
        "attachments": [],
    }


def test_send_mail_with_from_arg(mocker):
    """
    Given -
        to, subject and replyTo arguments to send an email.

    When -
        trying to send an email

    Then -
        verify the context output is returned correctly and that the 'to' and 'replyTo' arguments were sent
        as a list of strings.
    """
    from EWSv2 import send_email

    mocker.patch.object(
        TestNormalCommands.MockClient, "get_account", return_value=MockAccount(primary_smtp_address="test@gmail.com")
    )
    send_email_mocker = mocker.patch.object(
        EWSv2,
        "send_email_to_mailbox",
        return_value=("", [{"Contents": "", "ContentsFormat": "text", "Type": "png", "File": "image.png", "FileID": "12345"}]),
    )

    client = TestNormalCommands.MockClient()
    results = send_email(
        client, {"to": "test@gmail.com", "subject": "test", "replyTo": "test1@gmail.com", "from": "somemail@what.ever"}
    )
    assert send_email_mocker.call_args.kwargs.get("to") == ["test@gmail.com"]
    assert send_email_mocker.call_args.kwargs.get("reply_to") == ["test1@gmail.com"]
    assert results[0].get("Contents") == {
        "from": "somemail@what.ever",
        "to": ["test@gmail.com"],
        "subject": "test",
        "attachments": [],
    }


def test_send_mail_with_trailing_comma(mocker):
    """
    Given -
        a 'subject' which is 'test' and 'to' which is 'test@gmail.com,' (ending with a comma),

    When -
        trying to send an email

    Then -
        verify that the 'to' field was extracted correctly and that the trailing comma was handled.
    """
    from EWSv2 import send_email

    mocker.patch.object(
        TestNormalCommands.MockClient, "get_account", return_value=MockAccount(primary_smtp_address="test@gmail.com")
    )
    send_email_mocker = mocker.patch.object(
        EWSv2,
        "send_email_to_mailbox",
        return_value=("", [{"Contents": "", "ContentsFormat": "text", "Type": "png", "File": "image.png", "FileID": "12345"}]),
    )

    client = TestNormalCommands.MockClient()
    results = send_email(client, {"to": "test@gmail.com,", "subject": "test"})
    assert send_email_mocker.call_args.kwargs.get("to") == ["test@gmail.com"]
    assert results[0].get("Contents") == {
        "from": "test@gmail.com",
        "to": ["test@gmail.com"],
        "subject": "test",
        "attachments": [],
    }


@pytest.mark.parametrize(
    "item_ids, should_throw_exception",
    [
        (["1"], False),
        (["1", "2"], False),
        (["1", "2", "3"], True),
        (["1", "2", "3", "4"], True),
    ],
)
def test_get_items_from_mailbox(mocker, item_ids, should_throw_exception):
    """
    Given -
        Case A: single ID which is valid
        Case B: two IDs which are valid
        Case C: two ids which are valid and one id == 3 which cannot be found
        Case D: two ids which are valid and one id == 3 which cannot be found and one id == 4 which is malformed

    When -
        executing get_items_from_mailbox function

    Then -
        Case A: make sure the ID is returned successfully
        Case B: make sure that IDs are returned successfully
        Case C: make sure an exception is raised
        Case D: make sure an exception is raised
    """
    mocker.patch("EWSv2.Item", side_effect=[MockItem(item_id=item_id) for item_id in item_ids])
    mocker.patch.object(TestNormalCommands.MockClient, "get_account", return_value=MockAccount())

    client = TestNormalCommands.MockClient()
    if should_throw_exception:
        with pytest.raises(Exception):
            client.get_items_from_mailbox(None, item_ids=item_ids)
    else:
        assert client.get_items_from_mailbox(None, item_ids=item_ids) == item_ids


def test_categories_parse_item_as_dict():
    """
    Given -
        a Message with categories.

    When -
        running the parse_item_as_dict function.

    Then -
        verify that the categories were parsed correctly.
    """
    from EWSv2 import parse_item_as_dict

    message = Message(
        subject="message4",
        message_id="message4",
        text_body="Hello World",
        body="message4",
        datetime_received=EWSDateTime(2021, 7, 14, 13, 10, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_sent=EWSDateTime(2021, 7, 14, 13, 9, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_created=EWSDateTime(2021, 7, 14, 13, 11, 00, tzinfo=EWSTimeZone("UTC")),
        categories=["Purple category", "Orange category"],
    )

    return_value = parse_item_as_dict(message, False)
    assert return_value.get("categories") == ["Purple category", "Orange category"]


def test_parse_incident_from_item(mocker):
    """
    Given -
        a Message with attachments contains non-ASCII characters.

    When -
        running the parse_incident_from_item function.

    Then -
        verify that the attachments were parsed correctly.
    """
    from EWSv2 import parse_incident_from_item
    from exchangelib.attachments import AttachmentId, ItemAttachment

    mocker.patch("EWSv2.fileResult")
    message = Message(
        subject="message4",
        message_id="message4",
        text_body="Hello World",
        body="message4",
        datetime_received=EWSDateTime(2021, 7, 14, 13, 10, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_sent=EWSDateTime(2021, 7, 14, 13, 9, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_created=EWSDateTime(2021, 7, 14, 13, 11, 00, tzinfo=EWSTimeZone("UTC")),
        id="message4",
        attachments=[
            ItemAttachment(
                item=Item(mime_content=b"\x80\x81\x82"),
                attachment_id=AttachmentId(),
                last_modified_time=EWSDate(year=2021, month=1, day=25),
            ),
        ],
    )

    return_value = parse_incident_from_item(message, is_fetch=False, mark_as_read=False)
    assert return_value.get("attachment")


def test_list_parse_item_as_dict():
    """
    Given -
        a Message where effective rights is a list.

    When -
        running the parse_item_as_dict function.

    Then -
        verify that the object is parsed correctly.
    """
    from EWSv2 import parse_item_as_dict
    from exchangelib.properties import EffectiveRights

    message = Message(
        subject="message4",
        message_id="message4",
        text_body="Hello World",
        body="message4",
        datetime_received=EWSDateTime(2021, 7, 14, 13, 10, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_sent=EWSDateTime(2021, 7, 14, 13, 9, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_created=EWSDateTime(2021, 7, 14, 13, 11, 00, tzinfo=EWSTimeZone("UTC")),
        effective_rights=[EffectiveRights(), EffectiveRights()],
    )

    return_value = parse_item_as_dict(message, False)
    effetive_right_res = return_value.get("effective_rights")
    assert type(effetive_right_res) is list
    assert len(effetive_right_res) == 2


def test_parse_item_as_dict_with_empty_field():
    """
    Given -
        a Message where effective rights is None and other fields are false/empty strings.

    When -
        running the parse_item_as_dict function.

    Then -
        effective rights field was removed from response other empty\negative fields aren't.
    """
    from EWSv2 import parse_item_as_dict

    message = Message(
        subject="message4",
        message_id="message4",
        text_body="Hello World",
        body="",
        datetime_received=EWSDateTime(2021, 7, 14, 13, 10, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_sent=EWSDateTime(2021, 7, 14, 13, 9, 00, tzinfo=EWSTimeZone("UTC")),
        datetime_created=EWSDateTime(2021, 7, 14, 13, 11, 00, tzinfo=EWSTimeZone("UTC")),
        effective_rights=None,
        is_read=False,
    )

    return_value = parse_item_as_dict(message, False)
    assert "effective_rights" not in return_value
    assert return_value["body"] == ""
    assert return_value["is_read"] is False


def test_get_entry_for_object_empty():
    from EWSv2 import get_entry_for_object

    obj: dict = {}
    assert get_entry_for_object("test", "keyTest", obj).readable_output == "There is no output results"


def test_get_entry_for_object():
    from EWSv2 import get_entry_for_object

    obj = {"a": 1, "b": 2}
    assert get_entry_for_object("test", "keyTest", obj).readable_output == "### test\n|a|b|\n|---|---|\n| 1 | 2 |\n"


def test_get_time_zone(mocker):
    """
    When -
        trying to send/reply an email we check the XSOAR user time zone

    Then -
        verify that info returns
    """
    from EWSv2 import get_time_zone

    mocker.patch.object(demisto, "callingContext", new={"context": {"User": {"timeZone": "Asia/Jerusalem"}}})
    results = get_time_zone()
    assert results.key == "Asia/Jerusalem"


def test_resolve_names_command_no_contact(mocker):
    """
    Given:
        Calling resolve_name_command
    When:
        Only a Mailbox is returned
    Then:
        The results are displayed correctly without FullContactInfo
    """
    from EWSv2 import resolve_name_command

    protocol = mocker.Mock()
    email = "1234@demisto.com"
    protocol.resolve_names.return_value = [Mailbox(email_address=email)]
    client = TestNormalCommands.MockClient()
    client.protocol = protocol

    result = resolve_name_command(client, {"identifier": "someIdentifier"})

    assert email in result.readable_output
    assert isinstance(result.outputs, list)
    assert email == list(result.outputs)[0].get("email_address")
    assert not list(result.outputs)[0].get("FullContactInfo")


def test_resolve_names_command_with_contact(mocker):
    """
    Given:
        Calling resolve_name_command
    When:
        A Mailbox, Contact tuple is returned
    Then:
        The results are displayed correctly with FullContactInfo
    """
    from EWSv2 import resolve_name_command

    protocol = mocker.Mock()
    email = "1234@demisto.com"
    number_label = "Bussiness2"
    phone_numbers = [
        PhoneNumber(label=number_label, phone_number="+972 058 000 0000"),
        PhoneNumber(label="Bussiness", phone_number="+972 058 000 0000"),
    ]
    protocol.resolve_names.return_value = [(Mailbox(email_address=email), Contact(phone_numbers=phone_numbers))]
    client = TestNormalCommands.MockClient()
    client.protocol = protocol

    result = resolve_name_command(client, {"identifier": "someIdentifier"})

    assert email in result.readable_output
    assert isinstance(result.outputs, list)
    context_output = result.outputs[0]
    assert email == context_output.get("email_address")

    assert any(number.get("label") == number_label for number in context_output.get("FullContactInfo").get("phoneNumbers"))


def test_resolve_names_command_no_result(mocker):
    """
    Given:
        Calling resolve_name_command
    When:
        ErrorNameResolutionNoResults is returned
    Then:
        A human readable string is returned
    """
    from EWSv2 import resolve_name_command

    protocol = mocker.Mock()
    protocol.resolve_names.return_value = [ErrorNameResolutionNoResults(value="No results")]
    client = TestNormalCommands.MockClient()
    client.protocol = protocol

    result = resolve_name_command(client, {"identifier": "someIdentifier"})

    assert result == "No results were found."


def test_parse_phone_number():
    """
    Given: A filled phone number and a Phonenumber with no backing number
    When: Calling parse_phone_number
    Then: Only get the context object when the phpone_number is populated
    """
    good_number = EWSv2.parse_phone_number(PhoneNumber(label="123", phone_number="123123123"))
    assert good_number.get("label")
    assert good_number.get("phone_number")
    assert not EWSv2.parse_phone_number(PhoneNumber(label="123"))


def test_switch_hr_headers():
    """
    Given: A context object
    When: switching headers using a given header switch dict
    Then: The keys that are present are switched
    """
    assert EWSv2.switch_hr_headers(
        {"willswitch": "1234", "wontswitch": "111", "alsoswitch": 5555},
        {"willswitch": "newkey", "alsoswitch": "annothernewkey", "doesnt_exiest": "doesnt break"},
    ) == {"annothernewkey": 5555, "newkey": "1234", "wontswitch": "111"}


@pytest.mark.parametrize(
    "input, output",
    [
        ("John Smith", "John Smith"),
        ("SomeName", "SomeName"),
        ("sip:test@test.com", "sip:test@test.com"),
        ("hello@test.com", "smtp:hello@test.com"),
    ],
)
def test_format_identifier(input, output):
    """
    Given: several inputs with and without prefixes, that are or arent mails
    When: calling format_identifier
    Then: Only mails without a prefix have smtp appended
    """
    assert EWSv2.format_identifier(input) == output


@pytest.mark.parametrize(
    "handle_inline_image",
    [pytest.param(True, id="handle_inline_image is True"), pytest.param(False, id="handle_inline_image is False")],
)
def test_get_message_for_body_type_no_body_type_with_html_body(handle_inline_image: bool):
    body = "This is a plain text body"
    html_body = "<p>This is an HTML body</p>"
    result = get_message_for_body_type(body, None, html_body, handle_inline_image)
    assert isinstance(result[0], HTMLBody)
    assert result[0] == HTMLBody(html_body)


def test_get_message_for_body_type_no_body_type_with_html_body_and_image_and_handle_image_is_true(mocker: MockerFixture):
    from exchangelib import FileAttachment

    mocker.patch.object(uuid, "uuid4", return_value="123456")
    body = "This is a plain text body"
    html_body = '<p>This is an HTML body</p><p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA"/></p>'
    result = get_message_for_body_type(body, None, html_body, True)
    assert isinstance(result[0], HTMLBody)
    assert isinstance(result[1][0], FileAttachment)
    assert result[0] == HTMLBody('<p>This is an HTML body</p><p><img src="cid:image0@123456_123456"/></p>')


def test_get_message_for_body_type_no_body_type_with_html_body_and_image_and_handle_image_is_false():
    """Test get_message_for_body_type with no body type, HTML body, and image without handle.

    Given:
        - A plain text body and an HTML body with an embedded image.

    When:
        - Calling get_message_for_body_type with no body type and handle set to False.

    Then:
        - Ensure the result is an instance of HTMLBody.
        - Ensure the result is a list.
        - Ensure the HTML body content matches the expected value.
    """
    body = "This is a plain text body"
    html_body = '<p>This is an HTML body</p><p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA"/></p>'
    result = get_message_for_body_type(body, None, html_body, False)
    assert isinstance(result[0], HTMLBody)
    assert isinstance(result[1], list)
    assert result[0] == HTMLBody(html_body)


def test_get_message_for_body_type_no_body_type_with_no_html_body():
    body = "This is a plain text body"
    result = get_message_for_body_type(body, None, None, True)
    assert isinstance(result[0], Body)
    assert result[0] == Body(body)


@pytest.mark.parametrize(
    "handle_inline_image",
    [pytest.param(True, id="handle_inline_image is True"), pytest.param(False, id="handle_inline_image is False")],
)
def test_get_message_for_body_type_html_body_type_with_html_body(handle_inline_image: bool):
    body = "This is a plain text body"
    html_body = "<p>This is an HTML body</p>"
    result = get_message_for_body_type(body, "html", html_body, handle_inline_image)
    assert isinstance(result[0], HTMLBody)
    assert result[0] == HTMLBody(html_body)


@pytest.mark.parametrize(
    "handle_inline_image",
    [pytest.param(True, id="handle_inline_image is True"), pytest.param(False, id="handle_inline_image is False")],
)
def test_get_message_for_body_type_text_body_type_with_html_body(handle_inline_image: bool):
    body = "This is a plain text body"
    html_body = "<p>This is an HTML body</p>"
    result = get_message_for_body_type(body, "text", html_body, handle_inline_image)
    assert isinstance(result[0], Body)
    assert result[0] == Body(body)


def test_get_message_for_body_type_html_body_type_with_no_html_body():
    body = "This is a plain text body"
    result = get_message_for_body_type(body, "html", None, True)
    assert isinstance(result[0], Body)
    assert result[0] == Body(body)


def test_get_message_for_body_type_text_body_type_with_no_html_body():
    body = "This is a plain text body"
    result = get_message_for_body_type(body, "text", None, True)
    assert isinstance(result[0], Body)
    assert result[0] == Body(body)


@pytest.mark.parametrize(
    "handle_inline_image",
    [pytest.param(True, id="handle_inline_image is True"), pytest.param(False, id="handle_inline_image is False")],
)
def test_get_message_for_body_type_text_body_type_with_html_body_no_body(handle_inline_image):
    """
    Given: html_body, no body, the default 'text' as body_type.
    When: Constructing the message body.
    Then: Assert that the result is an html body.
    """
    html_body = "<p>This is an HTML body</p>"
    result = get_message_for_body_type("", "text", html_body, handle_inline_image)
    assert isinstance(result[0], HTMLBody)
    assert result[0] == HTMLBody(html_body)


def test_parse_physical_address():
    assert parse_physical_address(
        PhysicalAddress(city="New York", country="USA", label="SomeLabel", state="NY", street="Broadway Ave.", zipcode=10001)
    ) == {"city": "New York", "country": "USA", "label": "SomeLabel", "state": "NY", "street": "Broadway Ave.", "zipcode": 10001}


def test_parse_item_as_dict_return_json_serializable():
    """
    Given:
        - A message with cc_recipients with an object that includes a non-serializable object (ItemId).
    When:
        - Calling parse_item_as_dict

    Then:
        - Verify that the received dict is json serializable,
        and that the ItemId appears both in the received dict and the json serialized object.
    """
    item = Message(cc_recipients=[Mailbox(item_id=ItemId(id="id123", changekey="change"))])
    item_as_dict = parse_item_as_dict(item, None)
    item_as_json = json.dumps(item_as_dict, ensure_ascii=False)
    assert isinstance((item_as_dict.get("cc_recipients", [])[0]).get("item_id"), dict)
    assert '"item_id": {"id": "id123", "changekey": "change"}' in item_as_json


@pytest.mark.parametrize(
    "attachment_name, content_id, is_inline, attachment_subject, expected_result",
    [
        pytest.param("image1.png", "", False, None, "image1.png"),
        pytest.param("image1.png", "123", True, None, "123-attachmentName-image1.png"),
        pytest.param("image1.png", None, False, None, "image1.png"),
        pytest.param(None, None, False, "Re: test", "Re: test"),
    ],
)
def test_get_attachment_name(attachment_name, content_id, is_inline, attachment_subject, expected_result):
    """
    Given:
        - case 1: attachment is not inline.
        - case 2: attachment is inline.
        - case 3: attachment is not inline.
        - case 4: attachment with no name, only subject.
    When:
        - get_attachment_name is called with LEGACY_NAME=FALSE
    Then:
        Only case 2 should add an ID to the attachment name.

    """
    assert (
        get_attachment_name(
            attachment_name=attachment_name, content_id=content_id, is_inline=is_inline, attachment_subject=attachment_subject
        )
        == expected_result
    )


@pytest.mark.parametrize(
    "attachment_name, content_id, is_inline, expected_result",
    [
        pytest.param("image1.png", "", False, "image1.png"),
        pytest.param("image1.png", "123", True, "image1.png"),
        pytest.param("image1.png", None, False, "image1.png"),
    ],
)
def test_get_attachment_name_legacy_name(mocker, attachment_name, content_id, is_inline, expected_result):
    """
    Given:
        - case 1: attachment is not inline.
        - case 1: attachment is inline.
        - case 3: attachment is not inline.
    When:
        - get_attachment_name is called with legacy_name=True
    Then:
        All cases should not add an ID to the attachment name.

    """
    mocker.patch.object(demisto, "params", return_value={"legacy_name": True})
    assert get_attachment_name(attachment_name=attachment_name, content_id=content_id, is_inline=is_inline) == expected_result


def test_parse_mime_content_with_quoted_printable():
    """
    Given:
        - A MIME item with quoted-printable encoded subject and UTF-8 encoded body.

    When:
        - The MIME item is cast to a message object.

    Then:
        - The subject should be correctly decoded.
        - The body of the email should be correctly parsed.
    """

    from EWSv2 import cast_mime_item_to_message

    class MockMimeItem:
        mime_content: str = ""

        def __init__(self, message: str):
            self.mime_content = message

    mime_content = "Subject: =?UTF-8?Q?Prueba_de_correo?=\n\nEste es un correo de prueba."
    mime_item = cast_mime_item_to_message(MockMimeItem(mime_content))
    expected_subject = "Prueba de correo"
    expected_body = "Este es un correo de prueba."

    assert mime_item["Subject"] == expected_subject, f"Expected subject '{expected_subject}', got '{mime_item['Subject']}'"
    assert mime_item.get_payload() == expected_body, f"Expected body '{expected_body}', got '{mime_item.get_payload()}'"


def test_get_item_as_eml(mocker):
    """
    Given
        - A quoted-printable encoded email returns.
    When
        - The "ews-get-items-as-eml" command is called.
    Then
        - The output contains the expected file name and content
    """
    from EWSv2 import get_item_as_eml
    from exchangelib.items import Item
    from exchangelib.properties import MessageHeader

    content = (
        b"MIME-Version: 1.0\n"
        b"Message-ID:\r\n"
        b" <message-test-idRANDOMVALUES@testing.com>\r\n"
        b'Content-Type: text/plain; charset="iso-8859-2"\r\n'
        b"Content-Transfer-Encoding: quoted-printable\r\n"
        b"X-FAKE-Header: HVALue\r\n"
        b"X-Who-header: whovALUE\n"
        b"DATE: 2023-12-16T12:04:45\r\n"
        b"\r\nHello"
    )

    item_headers = [
        MessageHeader(name="Mime-Version", value="1.0"),
        MessageHeader(name="Content-Type", value="application/ms-tnef"),
        MessageHeader(name="X-Fake-Header", value="HVALue"),
        MessageHeader(name="X-WHO-header", value="whovALUE"),
        # this is a header whose value is different. The field is limited to 1 by RFC
        MessageHeader(name="Date", value="2023-12-16 12:04:45"),
        MessageHeader(name="X-EXTRA-Missed-Header", value="EXTRA"),
    ]
    expected_data = (
        "MIME-Version: 1.0\r\n"
        # Python 3.12's email generator no longer folds an empty Message-ID onto a
        # separate continuation line, so the value stays on the same line as the header.
        "Message-ID: <message-test-idRANDOMVALUES@testing.com>\r\n"
        'Content-Type: text/plain; charset="iso-8859-2"\r\n'
        "Content-Transfer-Encoding: quoted-printable\r\n"
        "X-FAKE-Header: HVALue\r\n"
        "X-Who-header: whovALUE\r\n"
        "DATE: 2023-12-16T12:04:45\r\n"
        "X-EXTRA-Missed-Header: EXTRA\r\n"
        "\r\nHello"
    )
    mock_file_result = mocker.patch("EWSv2.fileResult")
    mocker.patch.object(
        TestNormalCommands.MockClient, "get_item_from_mailbox", return_value=Item(mime_content=content, headers=item_headers)
    )
    mocker.patch.object(
        TestNormalCommands.MockClient, "get_account", return_value=MockAccount(primary_smtp_address="test@gmail.com")
    )
    client = TestNormalCommands.MockClient()

    get_item_as_eml(client, {"item_id": "Inbox", "target_mailbox": "test@gmail.com"})
    mock_file_result.assert_called_once_with("demisto_untitled_eml.eml", expected_data)


@pytest.mark.parametrize("manual_username, expected_username", [("", "test@gmail.com"), ("test2@gmail.com", "test2@gmail.com")])
def test_get_client_from_params(mocker, manual_username, expected_username):
    """
    Given:
        - Parameters for EWS connection.
    When:
        - get_client_from_params is called.
    Then:
        - The expected EWS client is returned.
    """
    from EWSApiModule import EWSClient
    from EWSv2 import get_client_from_params
    from exchangelib.protocol import BaseProtocol

    mocker.patch.object(EWSClient, "_configure_auth", return_value=(None, None, None))

    params = {
        "credentials": {"identifier": "test@gmail.com", "password": "test_pass"},
        "impersonation": True,
        "defaultTargetMailbox": "test1@gmail.com",
        "maxFetch": 10,
        "ewsServer": "some_server_url",
        "authType": "Basic",
        "defaultServerVersion": "2016",
        "folder": "Test_Folder",
        "isPublicFolder": True,
        "requestTimeout": 60,
        "markAsRead": True,
        "domainAndUserman": manual_username,
        "insecure": False,
    }

    client = get_client_from_params(params)

    assert isinstance(client, EWSClient)
    assert client.client_id == expected_username
    assert client.client_secret == "test_pass"
    assert client.access_type == "impersonation"
    assert client.account_email == "test1@gmail.com"
    assert client.max_fetch == 10
    assert client.ews_server == "some_server_url"
    assert client.auth_type == "basic"
    assert client.version == "2016"
    assert client.folder_name == "Test_Folder"
    assert client.is_public_folder
    assert BaseProtocol.TIMEOUT == 60
    assert client.mark_as_read
    assert not client.insecure


def test_start_logging_does_not_leak_exchangelib_output_to_stdout(mocker, capfd):
    """
    Given:
        The instance Log Level is set to debug/verbose (is_debug_mode() is True), and a
        stdout StreamHandler is attached to the root logger (as the docker runner environment does).
    When:
        start_logging() has run and exchangelib emits its HTTP transaction dump via logging
        (e.g. "Request headers: {...}" and "Response XML: b'<xml/>'").
    Then:
        The exchangelib dump lines must NOT appear on real stdout (they would corrupt the
        returned entry JSON), but they MUST still be captured in the in-memory debug buffer
        so the error-path "Full debug log" feature keeps working.
    """
    import sys

    mocker.patch.object(EWSv2, "is_debug_mode", return_value=True)

    # Reset the module-level logging state so start_logging() re-initializes cleanly.
    if EWSv2.log_handler is not None:
        logging.getLogger().removeHandler(EWSv2.log_handler)
        for logger_name in EWSv2.EXCHANGELIB_LOGGERS:
            logging.getLogger(logger_name).removeHandler(EWSv2.log_handler)
    EWSv2.log_stream = None
    EWSv2.log_handler = None

    # Simulate the docker runner environment: a stdout handler on the root logger.
    stdout_handler = logging.StreamHandler(stream=sys.stdout)
    root_logger = logging.getLogger()
    root_logger.addHandler(stdout_handler)
    try:
        EWSv2.start_logging()

        exchangelib_logger = logging.getLogger("exchangelib")
        exchangelib_logger.debug("Request headers: {'X-Foo': 'bar'}")
        exchangelib_logger.debug("Response XML: b'<xml/>'")

        captured = capfd.readouterr()
        # The exchangelib dump must not reach stdout.
        assert "Request headers: {" not in captured.out
        assert "Response XML:" not in captured.out

        # But it must still be captured in the in-memory debug buffer.
        debug_log = EWSv2.log_stream.getvalue()
        assert "Request headers: {" in debug_log
        assert "Response XML:" in debug_log
        assert logging.getLogger("exchangelib").propagate is False
    finally:
        root_logger.removeHandler(stdout_handler)
        if EWSv2.log_handler is not None:
            logging.getLogger().removeHandler(EWSv2.log_handler)
            for logger_name in EWSv2.EXCHANGELIB_LOGGERS:
                logging.getLogger(logger_name).removeHandler(EWSv2.log_handler)
        EWSv2.log_stream = None
        EWSv2.log_handler = None