Python API

Exchange

class RPA.Email.Exchange.Exchange

Bases: object

Exchange is a library for sending, reading, and deleting emails. Exchange is interfacing with Exchange Web Services (EWS).

For more information about server settings, see this Microsoft support article.

Examples

Robot Framework

*** Settings ***
Library     RPA.Email.Exchange
Task Setup  Authorize  username=${ACCOUNT}  password=${PASSWORD}

*** Variables ***
${ACCOUNT}              ACCOUNT_NAME
${PASSWORD}             ACCOUNT_PASSWORD
${RECIPIENT_ADDRESS}    RECIPIENT
${IMAGES}               myimage.png
${ATTACHMENTS}          C:${/}files${/}mydocument.pdf

*** Tasks ***
Task of sending email
    Send Message  recipients=${RECIPIENT_ADDRESS}
    ...           subject=Exchange Message from RPA Robot
    ...           body=<p>Exchange RPA Robot message body<br><img src='myimage.png'/></p>
    ...           save=${TRUE}
    ...           html=${TRUE}
    ...           images=${IMAGES}
    ...           cc=EMAIL_ADDRESS
    ...           bcc=EMAIL_ADDRESS
    ...           attachments=${ATTACHMENTS}

Task of listing messages
    # Attachments are saved specifically with a keyword Save Attachments
    ${messages}=    List Messages
    FOR    ${msg}    IN    @{messages}
        Log Many    ${msg}
        ${attachments}=    Run Keyword If    "${msg}[subject]"=="about my orders"
        ...    Save Attachments
        ...    ${msg}
        ...    save_dir=${CURDIR}${/}savedir
    END
    # Using save_dir all attachments in listed messages are saved
    ${messages}=    List Messages
    ...    INBOX/Problems/sub1
    ...    criterion=subject:'about my orders'
    ...    save_dir=${CURDIR}${/}savedir2
    FOR    ${msg}    IN    @{messages}
        Log Many    ${msg}
    END

Task of moving messages
    Move Messages    criterion=subject:'about my orders'
    ...    source=INBOX/Processed Purchase Invoices/sub2
    ...    target=INBOX/Problems/sub1

Python

from RPA.Email.Exchange import Exchange

ex_account = "ACCOUNT_NAME"
ex_password = "ACCOUNT_PASSWORD"

mail = Exchange()
mail.authorize(username=ex_account, password=ex_password)
mail.send_message(
    recipients="RECIPIENT",
    subject="Message from RPA Python",
    body="RPA Python message body",
)

About criterion parameter

Following table shows possible criterion keys that can be used to filter emails. There apply to all keywords which have criterion parameter.

Key

Effective search

subject

subject to match

subject_contains

subject to contain

body

body to match

body_contains

body to contain

sender

sender (from) to match

sender_contains

sender (from) to contain

before

received time before this time

after

received time after this time

between

received time between start and end

category

categories to match

category_contains

categories to contain

importance

importance to match

Keys before, after and between at the moment support two different timeformats either %d-%m-%Y %H:%M or %d-%m-%Y. These keys also support special string NOW which can be used especially together with keyword Wait for message  criterion=after:NOW.

When giving time which includes hours and minutes then the whole time string needs to be enclosed into single quotes.

before:25-02-2022
after:NOW
between:'31-12-2021 23:50 and 01-01-2022 00:10'

Different criterion keys can be combined.

subject_contains:'new year' between:'31-12-2021 23:50 and 01-01-2022 00:10'

Please note that all values in the criterion that contain spaces need to be enclosed within single quotes.

In the following example the email subject is going to matched only against new not new year.

subject_contains:new year
ROBOT_LIBRARY_DOC_FORMAT = 'REST'
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
authorize(username: str, password: str, autodiscover: Optional[bool] = True, access_type: Optional[str] = 'DELEGATE', server: Optional[str] = None, primary_smtp_address: Optional[str] = None) → None

Connect to Exchange account

Parameters
  • username – account username

  • password – account password

  • autodiscover – use autodiscover or set it off

  • accesstype – default “DELEGATE”, other option “IMPERSONATION”

  • server – required for configuration options

  • primary_smtp_address – by default set to username, but can be set to be different than username

create_folder(folder_name: Optional[str] = None, parent_folder: Optional[str] = None) → bool

Create email folder

Parameters
  • folder_name – name for the new folder

  • parent_folder – name for the parent folder, by default INBOX

Returns

True if operation was successful, False if not

delete_folder(folder_name: Optional[str] = None, parent_folder: Optional[str] = None) → bool

Delete email folder

Parameters
  • folder_name – current folder name

  • parent_folder – name for the parent folder, by default INBOX

Returns

True if operation was successful, False if not

empty_folder(folder_name: Optional[str] = None, parent_folder: Optional[str] = None, delete_sub_folders: Optional[bool] = False) → bool

Empty email folder of all items

Parameters
  • folder_name – current folder name

  • parent_folder – name for the parent folder, by default INBOX

  • delete_sub_folders – delete sub folders or not, by default False

Returns

True if operation was successful, False if not

list_messages(folder_name: Optional[str] = None, criterion: Optional[str] = None, contains: Optional[bool] = False, count: Optional[int] = 100, save_dir: Optional[str] = None) → list

List messages in the account inbox. Order by descending received time.

Parameters
  • folder_name – name of the email folder, default INBOX

  • criterion – list messages matching criterion

  • contains – if matching should be done using contains matching and not equals matching, default False is means equals matching

  • count – number of messages to list

  • save_dir – set to path where attachments should be saved, default None (attachments are not saved)

list_unread_messages(folder_name: Optional[str] = None, criterion: Optional[str] = None, contains: Optional[bool] = False, count: Optional[int] = 100, save_dir: Optional[str] = None) → list

List unread messages in the account inbox. Order by descending received time.

Parameters
  • folder_name – name of the email folder, default INBOX

  • criterion – list messages matching criterion

  • contains – if matching should be done using contains matching and not equals matching, default False is means equals matching

  • count – number of messages to list

  • save_dir – set to path where attachments should be saved, default None (attachments are not saved)

move_message(msg: Optional[dict], target: Optional[str])

Move a message into target folder

Parameters
  • msg – dictionary of the message

  • target – path to target folder

Raises

AttributeError – if msg is not a dictionary containing id and changekey attributes

Example:

${messages}=    List Messages
...    INBOX
...    criterion=subject:about my orders
FOR    ${msg}    IN    @{messages}
    Run Keyword If    "${msg}[sender][email_address]"=="${priority_account}"
    ...    Move Message    ${msg}    target=INBOX / Problems / priority
END
move_messages(criterion: Optional[str] = '', source: Optional[str] = None, target: Optional[str] = None, contains: Optional[bool] = False) → bool

Move message(s) from source folder to target folder

Parameters
  • criterion – move messages matching this criterion

  • source – source folder

  • target – target folder

  • contains – if matching should be done using contains matching and not equals matching, default False is means equals matching

Returns

boolean result of operation, True if 1+ items were moved else False

Criterion examples:

  • subject:my message subject

  • body:something in body

  • sender:sender@domain.com

rename_folder(oldname: Optional[str] = None, newname: Optional[str] = None, parent_folder: Optional[str] = None) → bool

Rename email folder

Parameters
  • oldname – current folder name

  • newname – new name for the folder

  • parent_folder – name for the parent folder, by default INBOX

Returns

True if operation was successful, False if not

save_attachments(message: Union[dict, str], save_dir: Optional[str] = None, attachments_from_emls: Optional[bool] = False) → list

Save attachments in message into given directory

Parameters
  • message – dictionary or .eml filepath containing message details

  • save_dir – filepath where attachments will be saved

  • attachments_from_emls – if attachment is a EML file, set to True to save attachments from that EML file, default False

Returns

list of saved attachments

Example.

${messages}=    List Messages
FOR    ${msg}    IN    @{messages}}
    Save Attachments    ${msg}    %{ROBOT_ARTIFACTS}  True
END
${attachments}=  Save Attachments  ${CURDIR}${/}saved.eml  %{ROBOT_ARTIFACTS}
save_message(message: dict, filename: str) → list

Save email as .eml file

Parameters
  • message – dictionary containing message details

  • filename – name of the file to save message into

send_message(recipients: Union[List[str], str, None] = None, subject: Optional[str] = '', body: Optional[str] = '', attachments: Union[List[str], str, None] = None, html: Optional[bool] = False, images: Union[List[str], str, None] = None, cc: Union[List[str], str, None] = None, bcc: Union[List[str], str, None] = None, save: Optional[bool] = False) → None

Keyword for sending message through connected Exchange account.

Parameters
  • recipients – list of email addresses

  • subject – message subject, defaults to “”

  • body – message body, defaults to “”

  • attachments – list of filepaths to attach, defaults to None

  • html – if message content is in HTML, default False

  • images – list of filepaths for inline use, defaults to None

  • cc – list of email addresses

  • bcc – list of email addresses

  • save – is sent message saved to Sent messages folder or not, defaults to False

Email addresses can be prefixed with ex: to indicate an Exchange account address.

At least one target needs to exist for recipients, cc or bcc.

wait_for_message(criterion: Optional[str] = '', timeout: Optional[float] = 5.0, interval: Optional[float] = 1.0, contains: Optional[bool] = False, save_dir: Optional[str] = None) → Any

Wait for email matching criterion to arrive into INBOX.

Parameters
  • criterion – wait for message matching criterion

  • timeout – total time in seconds to wait for email, defaults to 5.0

  • interval – time in seconds for new check, defaults to 1.0 (minimum)

  • contains – if matching should be done using contains matching and not equals matching, default False is means equals matching THIS PARAMETER IS DEPRECATED AS OF rpaframework 12.9.0

  • save_dir – set to path where attachments should be saved, default None (attachments are not saved)

Returns

list of messages

exception RPA.Email.Exchange.NoRecipientsError

Bases: ValueError

Raised when email to be sent does not have any recipients, cc or bcc addresses.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

RPA.Email.Exchange.mailbox_to_email_address(mailbox)