Add Gmail Labels

Add GMail labels to messages matching criterion and if given, source folder

Arguments

Argument Type Default value Description
labelsnullcomma separated list of labels to add
criterionnulllabel messages matching criterion
source_folderstrNonelook for messages in this folder, default all folders
param labels:comma separated list of labels to add
param criterion:
 label messages matching criterion
param source_folder:
 look for messages in this folder, default all folders
return:status of the operation

Examples

Add Gmail Labels  customer1   SUBJECT "order confirmation"
Add Gmail Labels  wip         SUBJECT "order confirmation"   customerfolder

Authorize

Authorize user to SMTP and IMAP servers.

Arguments

Argument Type Default value Description
accountstr, NoneNoneuser account as string, defaults to None
passwordstr, NoneNoneuser password as string, defaults to None
smtp_serverstr, NoneNoneSMTP server address, defaults to None
imap_serverstr, NoneNoneIMAP server address, defaults to None
smtp_portint, NoneNoneSMTP server port, defaults to None (587 for SMTP)
imap_portint, NoneNoneIMAP server port, defaults to None
is_oauthboolFalseUse XOAUTH2 protocol with a base64 encoded OAuth2 string as password
param account:user account as string, defaults to None
param password:user password as string, defaults to None
param smtp_server:
 SMTP server address, defaults to None
param imap_server:
 IMAP server address, defaults to None
param smtp_port:
 SMTP server port, defaults to None (587 for SMTP)
param imap_port:
 IMAP server port, defaults to None
param is_oauth:Use XOAUTH2 protocol with a base64 encoded OAuth2 string as password

Will use separately set credentials or those given in keyword call.

Examples

Authorize    ${username}   ${password}  smtp_server=smtp.gmail.com  smtp_port=587

Authorize Imap

Authorize to IMAP server.

Arguments

Argument Type Default value Description
accountstr, NoneNoneIMAP account name, defaults to None
passwordstr, NoneNoneIMAP account password, defaults to None
imap_serverstr, NoneNoneIMAP server address, defaults to None
imap_portint, NoneNoneIMAP server port, defaults to None
is_oauthboolFalseUse XOAUTH2 protocol with a base64 encoded OAuth2 string as password
param account:IMAP account name, defaults to None
param password:IMAP account password, defaults to None
param imap_server:
 IMAP server address, defaults to None
param imap_port:
 IMAP server port, defaults to None
param is_oauth:Use XOAUTH2 protocol with a base64 encoded OAuth2 string as password

Can be called without giving any parameters if library has been initialized with necessary information and/or keyword Set Credentials has been called.

Examples

Authorize IMAP    ${username}   ${password}  imap.gmail.com  993

Authorize Smtp

Authorize to SMTP server.

Arguments

Argument Type Default value Description
accountstr, NoneNoneSMTP account name, defaults to None
passwordstr, NoneNoneSMTP account password, defaults to None
smtp_serverstr, NoneNoneSMTP server address, defaults to None
smtp_portint, NoneNoneSMTP server port, defaults to None (587 for SMTP)
is_oauthboolFalseUse XOAUTH2 protocol with a base64 encoded OAuth2 string as password
param account:SMTP account name, defaults to None
param password:SMTP account password, defaults to None
param smtp_server:
 SMTP server address, defaults to None
param smtp_port:
 SMTP server port, defaults to None (587 for SMTP)
param is_oauth:Use XOAUTH2 protocol with a base64 encoded OAuth2 string as password

Can be called without giving any parameters if library has been initialized with necessary information and/or keyword Set Credentials has been called.

Examples

Authorize SMTP    ${username}   ${password}  smtp.gmail.com  587

Create Folder

Create email folder

Arguments

Argument Type Default value Description
folder_namestrNonename for the new folder
param folder_name:
 name for the new folder
return:True if operation was successful, False if not

Examples

Create Folder   filtered

Delete Folder

Delete email folder

Arguments

Argument Type Default value Description
folder_namestrNonecurrent folder name
param folder_name:
 current folder name
return:True if operation was successful, False if not

Examples

Delete Folder   filtered

Delete Message

Delete single message from server based on criterion.

Arguments

Argument Type Default value Description
criterionstr, dictNonefilter messages based on this search, can also be a message dictionary
source_folderstrNonedefaults to already selected folder, but can be set to delete message in a specific folder
param criterion:
 filter messages based on this search, can also be a message dictionary
param source_folder:
 defaults to already selected folder, but can be set to delete message in a specific folder
return:True if success, False if not

If criterion does not return exactly 1 message then delete is not done.

Examples

Delete Message  SUBJECT "Greetings RPA developer"

Delete Messages

Delete messages from server based on criterion.

Arguments

Argument Type Default value Description
criterionstr, listNonefilter messages based on this search, can also be a list of message dictionaries
limitintNonemaximum number of message to delete
source_folderstrNonedefaults to already selected folder, but can be set to delete message in a specific folder
param criterion:
 filter messages based on this search, can also be a list of message dictionaries
param limit:maximum number of message to delete
param source_folder:
 defaults to already selected folder, but can be set to delete message in a specific folder
return:True if success, False if not

Examples

Delete Messages  SUBJECT Greetings

Do Message Actions

Do actions to messages matching criterion and if given, source folder

Arguments

Argument Type Default value Description
criterionstrperform actions on messages matching this
actionslistNonelist of actions to perform on matching messages
source_folderstrNonelook for messages in this folder, default all folders
target_folderstrNonecan be file path or email folder (for example action: msg_copy)
labelsstrNonecomma separated list of labels (for example action: glabel_add)
limitintNonemaximum number of messages (for example action: msg_delete)
overwriteboolFalseto control if file should overwrite (for example action: msg_attachment_save)
prefixstrNoneprefix to be added into filename (for example: msg_save)

Actions can be:

  • msg_copy
  • msg_delete
  • msg_flag
  • msg_unflag
  • msg_read
  • msg_unread
  • msg_save
  • msg_attachment_save
  • glabel_add
  • glabel_remove

Result object contains following attributes:

  • actions_done, number of messages on which action was performed
  • message_count, number of messages matching criterion
  • ids, message ids matching criterion
  • uids, dictionary of message uids and message content
param criterion:
 perform actions on messages matching this
param actions:list of actions to perform on matching messages
param source_folder:
 look for messages in this folder, default all folders
param target_folder:
 can be file path or email folder (for example action: msg_copy)
param labels:comma separated list of labels (for example action: glabel_add)
param limit:maximum number of messages (for example action: msg_delete)
param overwrite:
 to control if file should overwrite (for example action: msg_attachment_save)
param prefix:prefix to be added into filename (for example: msg_save)
return:result object

Examples

${actions}=   Create List  msg_unflag  msg_read  msg_save  msg_attachment_save
Do Message Actions    SUBJECT "Order confirmation"
...                   ${actions}
...                   source_folder=XXX
...                   target_folder=${CURDIR}
...                   overwrite=True

Email To Document

Convert a raw e-mail into a Word document.

Arguments

Argument Type Default value Description
input_sourcestr, Path, BinaryIO, bytesnullPath, bytes or file-like object with the input raw e-mail content
output_pathstr, PathnullWhere to save the output docx file

This keyword extracts the HTML (or Text) content from the passed input e-mail and saves it into docx format at the provided output path.

param input_source:
 Path, bytes or file-like object with the input raw e-mail content
param output_path:
 Where to save the output docx file

Examples

Robot Framework

Convert email to docx
    ${mail_file} =     Get Work Item File    mail.eml
    Email To Document    ${mail_file}    ${OUTPUT_DIR}${/}mail.docx

Python

from pathlib import Path
from RPA.Email.ImapSmtp import ImapSmtp
from RPA.Robocorp.WorkItems import WorkItems

lib_work = WorkItems()
lib_mail = ImapSmtp()

def convert_email_to_docx():
    lib_work.get_input_work_item()
    mail_file = lib_work.get_work_item_file("mail.eml")
    lib_mail.email_to_document(mail_file, Path("./output") / "mail.docx")

convert_email_to_docx()

Flag Messages

Mark messages as flagged

Arguments

Argument Type Default value Description
criterionstr, dictNonemark messages matching criterion
unflagboolFalseto mark messages as not flagged
param criterion:
 mark messages matching criterion
param unflag:to mark messages as not flagged
return:successful operations (int), matching messages (int)

Examples

${flagged}  ${oftotal}    Flag Messages   SUBJECT rpa
${unflagged}  ${oftotal}  Flag Messages   SUBJECT rpa  unflag=True

Generate Oauth String

Generate and return an OAuth2 string compatible with the IMAP/POP/SMTP XOAUTH2 protocol.

Arguments

Argument Type Default value Description
usernamestrnullThe e-mail address you're going to send the e-mail with.
access_tokenstrnullAccess token string found in the dictionary obtained with Get OAuth Token or Refresh OAuth Token.

This string usually gets passed to the Authorize keyword as password when is_oauth=${True}.

param username:The e-mail address you're going to send the e-mail with.
param access_token:
 Access token string found in the dictionary obtained with Get OAuth Token or Refresh OAuth Token.
returns:Base64 encoded string packing these credentials and replacing the legacy password when enabling the OAuth2 flow.

Example: Robot Framework

*** Tasks ***
Authorize ImapSmtp
    ${password} =   Generate OAuth String    ${username}
    ...    ${token}[access_token]
    Authorize    account=${username}    is_oauth=${True}
    ...     password=${password}

Generate Oauth Url

Generates an authorization URL which must be opened by the user to start the OAuth2 flow and obtain an authorization code as response.

Arguments

Argument Type Default value Description
client_idstrnullClient app ID. (generated by the provider)
param client_id:
 Client app ID. (generated by the provider)
returns:Authorization URL string not containing any sensitive info in it.

Example: Robot Framework

*** Tasks ***
Start OAuth Flow
    ${auth_url} =    Generate OAuth URL
    ...     client_id=810482312368-19htmcgcj*******googleusercontent.com
    Log     Start OAuth2 flow: ${auth_url}

Get Decoded Email Body

Decodes email body and extracts its text/html content.

Arguments

Argument Type Default value Description
messagenullRaw 7-bit message body input e.g. from imaplib. Double encoded in quoted-printable and latin-1
html_firstboolFalsePrioritize html extraction over text when this is True

Automatically detects character set if the header is not set.

param message:Raw 7-bit message body input e.g. from imaplib. Double encoded in quoted-printable and latin-1
param html_first:
 Prioritize html extraction over text when this is True
returns:Message body as unicode string and a boolean telling if the message has attachments

Get Folder List

Get list of folders on the server

Arguments

Argument Type Default value Description
subdirectorystrNonelist subdirectories for this folder
patternstrNonelist folders matching this pattern
param subdirectory:
 list subdirectories for this folder
param pattern:list folders matching this pattern
return:list of folders

Examples

@{folders}  Get Folder List
@{folders}  Get Folder List  pattern=important
@{folders}  Get Folder List  subdirectory=sub

Get Oauth Token

Exchanges the code obtained previously with Generate OAuth URL for a token.

Arguments

Argument Type Default value Description
client_secretstrnullClient app secret. (generated by the provider)
response_urlstrnullThe final URL containing the authorization code found in the address bar after authenticating and authorizing the Client app through the authorization URL.
param client_secret:
 Client app secret. (generated by the provider)
param response_url:
 The final URL containing the authorization code found in the address bar after authenticating and authorizing the Client app through the authorization URL.
returns:A dictionary containing the access & refresh token, plus metadata.

Example: Robot Framework

*** Tasks ***
Finish OAuth Flow
    ${token} =      Get OAuth Token
    ...     client_secret=GOCSPX-******mqZAW89
    ...     response_url=${resp_url}  # redirect of `Generate OAuth URL`

List Messages

Return list of messages matching criterion.

Arguments

Argument Type Default value Description
criterionstrlist emails matching this, defaults to ""
source_folderstrNonelist messages from this folder
readonlyboolTrueset False if you want to mark matching messages as read
param criterion:
 list emails matching this, defaults to ""
param source_folder:
 list messages from this folder
param readonly:set False if you want to mark matching messages as read
return:list of messages

Note. listing messages without source_folder might take a long time

Examples

@{emails}  List Messages  SUBJECT "rpa task"
FOR  ${email}  IN  @{EMAILS}
    Log  ${email}[Subject]
    Log  ${email}[From]
    Log  ${email}[Date]
    Log  ${email}[Delivered-To]
    Log  ${email}[Received]
    Log  ${email}[Has-Attachments]
    Log  ${email}[uid]
END

Mark As Read

Mark messages as read

Arguments

Argument Type Default value Description
criterionstr, dictNonemark messages matching criterion
unreadboolFalseto mark messages as not read
param criterion:
 mark messages matching criterion
param unread:to mark messages as not read
return:successful operations (int), matching messages (int)

Examples

${read}  ${oftotal}  Mark As Read   SUBJECT rpa

Mark As Unread

Mark messages as not read

Arguments

Argument Type Default value Description
criterionstr, dictNonemark messages matching criterion
param criterion:
 mark messages matching criterion
return:successful operations (int), matching messages (int)

Examples

${unread}  ${oftotal}  Mark As Unread   SUBJECT rpa

Move Messages

Move messages from source folder to target folder

Arguments

Argument Type Default value Description
criterionstr, dictNonemove messages matching criterion
target_folderstrNonewhere messages should be move into
source_folderstrNonelocation of the messages, default INBOX
param criterion:
 move messages matching criterion
param source_folder:
 location of the messages, default INBOX
param target_folder:
 where messages should be move into
return:True if all move operations succeeded, False if not

Examples

${result}=    Move Messages
...    criterion=SUBJECT "order confirmation 32"
...    target_folder=yyy

${result}=    Move Messages
...    criterion=ALL
...    source_folder=yyy
...    target_folder=XXX

Move Messages By Ids

Move message by their Message-ID's from source folder to target folder

Arguments

Argument Type Default value Description
message_idsstr, Listnullone Message-ID as string or list of Message-IDs
target_folderstrnullwhere messages should be move into
source_folderstrnulllocation of the messages, default INBOX
use_gmail_searchboolFalseset to True to use Rfc822msgid search, default is HEADER Message-ID search
param message_ids:
 one Message-ID as string or list of Message-IDs
param source_folder:
 location of the messages, default INBOX
param target_folder:
 where messages should be move into
param use_gmail_search:
 set to True to use Rfc822msgid search, default is HEADER Message-ID search
return:True if all move operations succeeded, False if not

Refresh Oauth Token

Refreshes the token as the access one usually expires after 1h and the refresh one never expires. (as long as it doesn't get revoked)

Arguments

Argument Type Default value Description
client_idstrnullClient app ID. (generated by the provider)
client_secretstrnullClient app secret. (generated by the provider)
tokendictnullFull token dictionary previously obtained with Get OAuth Token.
param client_id:
 Client app ID. (generated by the provider)
param client_secret:
 Client app secret. (generated by the provider)
param token:Full token dictionary previously obtained with Get OAuth Token.
returns:A token dictionary containing a new access token and updated metadata.

Example: Robot Framework

*** Tasks ***
Refresh OAuth Flow
    ${token} =      Refresh OAuth Token
    ...     client_id=810482312368-19htmcgcj*******googleusercontent.com
    ...     client_secret=GOCSPX-******mqZAW89
    ...     token=${token}  # from `Get OAuth Token`

Remove Gmail Labels

Remove GMail labels to messages matching criterion and if given, source folder

Arguments

Argument Type Default value Description
labelsnullcomma separated list of labels to remove
criterionnullunlabel messages matching criterion
source_folderstrNonelook for messages in this folder, default all folders
param labels:comma separated list of labels to remove
param criterion:
 unlabel messages matching criterion
param source_folder:
 look for messages in this folder, default all folders
return:status of the operation

Examples

Remove Gmail Labels  wip  SUBJECT "order confirmation"
Remove Gmail Labels  wip  SUBJECT "order confirmation"  customerfolder

Rename Folder

Rename email folder

Arguments

Argument Type Default value Description
oldnamestrNonecurrent folder name
newnamestrNonenew name for the folder
suppress_errorboolFalseto silence warning message, defaults to False
param oldname:current folder name
param newname:new name for the folder
param suppress_error:
 to silence warning message, defaults to False
return:True if operation was successful, False if not

Examples

Rename Folder   subfolder   filtered

Save Attachment

Save mail attachment of a single given email on the local disk.

Arguments

Argument Type Default value Description
messagedict, Messagenullmessage item
target_folderstr, Nonenulllocal folder for saving attachments to (needs to exist), defaults to user's home directory if None
overwriteboolnulloverwrite existing file if True, defaults to False
prefixstr, NoneNoneoptional filename prefix added to the attachments, empty by default
param message:message item
param target_folder:
 local folder for saving attachments to (needs to exist), defaults to user's home directory if None
param overwrite:
 overwrite existing file if True, defaults to False
param prefix:optional filename prefix added to the attachments, empty by default
return:list of saved attachments (list of absolute filepaths) in one email

Examples

@{emails} =    List Messages    ALL
FOR    ${email}    IN    @{emails}
    IF    ${email}[Has-Attachments]
        Log To Console    Saving attachment for: ${email}[Subject]
        ${attachments} =    Save Attachment
        ...    ${email}
        ...    target_folder=${CURDIR}
        ...    overwrite=${True}
        Log To Console    Saved attachments: ${attachments}
    END
END

Save Attachments

Save mail attachments of emails matching criterion on the local disk.

Arguments

Argument Type Default value Description
criterionstrattachments are saved for mails matching this, defaults to ""
target_folderstr, NoneNonelocal folder for saving attachments to (needs to exist), defaults to user's home directory if None
overwriteboolFalseoverwrite existing file if True, defaults to False
prefixstr, NoneNoneoptional filename prefix added to the attachments, empty by default
param criterion:
 attachments are saved for mails matching this, defaults to ""
param target_folder:
 local folder for saving attachments to (needs to exist), defaults to user's home directory if None
param overwrite:
 overwrite existing file if True, defaults to False
param prefix:optional filename prefix added to the attachments, empty by default
return:list of saved attachments (absolute file paths) of all emails

Examples

${attachments} =    Save Attachments    SUBJECT "rpa task"
...    target_folder=${CURDIR}${/}messages  overwrite=${True}
FOR  ${file}  IN  @{attachments}
    OperatingSystem.File Should Exist  ${file}
END

Save Messages

Save messages based on criteria and store them to target folder with attachment files.

Arguments

Argument Type Default value Description
criterionstr, dict, list, NoneNonefilter messages based on this, defaults to ""
target_folderstr, NoneNonepath to folder where message are saved, defaults to None
prefixstr, NoneNoneoptional filename prefix added to the attachments, empty by default

Does not save message if target_folder is not given.

param criterion:
 filter messages based on this, defaults to ""
param target_folder:
 path to folder where message are saved, defaults to None
param prefix:optional filename prefix added to the attachments, empty by default
return:True if succeeded, False otherwise

Examples

Save Messages  SUBJECT Important message  target_folder=${USERDIR}${/}messages

Select Folder

Select folder by name

Arguments

Argument Type Default value Description
folder_namestrINBOXname of the folder to select
readonlyboolFalseif set to True then message flags are not modified
param folder_name:
 name of the folder to select
param readonly:if set to True then message flags are not modified
return:message count in the selected folder

Returns number of messages in the folder or exception if folder does not exist on the server.

Examples

Select Folder   subfolder

Send Message

Send SMTP email

Arguments

Argument Type Default value Description
senderstrnullwho is sending, ie. 'from'
recipientsList[str], strnullwho is receiving, ie. 'to'
subjectstrmail subject field
bodystrmail body content
attachmentsstr, List[str], NoneNonelist of filepaths to attach
htmlboolFalseif message content is in HTML, default False
imagesstr, List[str], NoneNonelist of filepaths for inline images
ccstr, List[str], NoneNonelist of email addresses for email 'cc' field
bccstr, List[str], NoneNonelist of email addresses for email 'bcc' field
attachment_positionAttachmentPosition, NoneTOPcontent position for attachment, default top
param sender:who is sending, ie. 'from'
param recipients:
 who is receiving, ie. 'to'
param subject:mail subject field
param body:mail body content
param attachments:
 list of filepaths to attach
param html:if message content is in HTML, default False
param images:list of filepaths for inline images
param cc:list of email addresses for email 'cc' field
param bcc:list of email addresses for email 'bcc' field
param attachment_position:
 content position for attachment, default top

Valid sender values:

Examples

Send Message  sender@domain.com  recipient@domain.com
...           cc=need_to_know@domain.com
...           bcc=hidden_copy@domain.com
...           subject=Greetings Software Robot Developer
...           body=${email_body}
...           attachments=${CURDIR}${/}report.pdf

# Fixing attachments to the bottom of the content
Send Message  sender@domain.com  recipient@domain.com
...           subject=Greetings Software Robot Developer
...           body=${email_body}
...           attachments=${CURDIR}${/}report.pdf
...           attachment_position=bottom

Send Smtp Hello

Send hello message to SMTP server.

Required step when creating SMTP connection.

Set Credentials

Set credentials

Arguments

Argument Type Default value Description
accountstr, NoneNoneuser account as string, defaults to None
passwordstr, NoneNoneuser password as string, defaults to None
param account:user account as string, defaults to None
param password:user password as string, defaults to None

Examples

Set Credentials   ${username}   ${password}
Authorize

Unflag Messages

Mark messages as not flagged

Arguments

Argument Type Default value Description
criterionstr, dictNonemark messages matching criterion
param criterion:
 mark messages matching criterion
return:successful operations (int), matching messages (int)

Examples

${unflagged}  ${oftotal}  Unflag Messages   SUBJECT rpa

Wait For Message

Wait for email matching criterion to arrive into mailbox.

Arguments

Argument Type Default value Description
criterionstrmessage filter to wait for, defaults to ""
timeoutfloat5.0total time in seconds to wait for email, defaults to 5.0
intervalfloat1.0time in seconds for new check, defaults to 1.0
readonlyboolTrueset False if you want to mark matching messages as read
param criterion:
 message filter to wait for, defaults to ""
param timeout:total time in seconds to wait for email, defaults to 5.0
param interval:time in seconds for new check, defaults to 1.0
param readonly:set False if you want to mark matching messages as read
return:list of messages

Examples

@{emails}  Wait For Message  SUBJECT "rpa task"  timeout=300  interval=10