def mark_as_read(service, query):
    messages_to_mark = search_messages(service, query)
    return service.users().messages().batchModify(
        userId='me',
        body={
            'ids': [msg['id'] for msg in messages_to_mark],
            'removeLabelIds': ['UNREAD']
        }).execute()
Beispiel #2
0
def delete_messages(service, query):
    messages_to_delete = search_messages(service, query)
    # it's possible to delete a single message with the delete API, like this:
    # service.users().messages().delete(userId='me', id=msg['id'])
    # but it's also possible to delete all the selected messages with one query, batchDelete
    return service.users().messages().batchDelete(
        userId='me', body={
            'ids': [msg['id'] for msg in messages_to_delete]
        }).execute()
Beispiel #3
0
def mark_as_unread(service, query):
    messages_to_mark = search_messages(service, query)
    if len(messages_to_mark) == 0: # No emails found
        return print("No emails found")
    else:
        print("="*50)
        for message_id in messages_to_mark:
            msg = service.users().messages().get(userId='me', id=message_id['id'], format='full').execute()
            payload = msg['payload']
            headers = payload.get("headers")
            if headers:
                # this section prints email basic info & creates a folder for the email
                for header in headers:
                    name = header.get("name")
                    value = header.get("value")
                    if name == 'From':
                        # we print the From address
                        print("From:", value)
                    if name == "To":
                        # we print the To address
                        print("To:", value)
                    if name == "Subject":
                        # we print the Subject
                        print("Subject:", value)
                    if name == "Date":
                        # we print the date when the message was sent
                        print("Date:", value)
            print("="*50)
            print("MARKED AS UNREAD")
    return service.users().messages().batchModify(
        userId='me',
        body={
            'ids': [ msg['id'] for msg in messages_to_mark ],
            'addLabelIds': ['UNREAD']
        }
    ).execute()
                # we will also handle emails with the same subject name
                folder_counter = 0
                while os.path.isdir(folder_name):
                    folder_counter += 1
                    # we have the same folder name, add a number next to it
                    if folder_name[-1].isdigit() and folder_name[-2] == "_":
                        folder_name = f"{folder_name[:-2]}_{folder_counter}"
                    elif folder_name[-2:].isdigit() and folder_name[-3] == "_":
                        folder_name = f"{folder_name[:-3]}_{folder_counter}"
                    else:
                        folder_name = f"{folder_name}_{folder_counter}"
                os.mkdir(folder_name)
                print("Subject:", value)
            if name.lower() == "date":
                # we print the date when the message was sent
                print("Date:", value)
    if not has_subject:
        # if the email does not have a subject, then make a folder with "email" name
        # since folders are created based on subjects
        if not os.path.isdir(folder_name):
            os.mkdir(folder_name)
    parse_parts(service, parts, folder_name, message)
    print("="*50)

if __name__ == "__main__":
    service = gmail_authenticate()
    # get emails that match the query you specify from the command lines
    results = search_messages(service, sys.argv[1])
    # for each email matched, read it (output plain/text to console & save HTML and attachments)
    for msg in results:
        read_message(service, msg)
                          help='a search query that selects emails to mark')
    parser_3.add_argument(
        'read_status',
        type=bool,
        help='Whether to mark the message as unread, or as read')
    parser_3.set_defaults(action='mark')
    parser_4 = subparsers.add_parser(
        'search', help='Marks a set of emails as read or unread')
    parser_4.add_argument('query',
                          type=str,
                          help='a search query, which messages to display')
    parser_4.set_defaults(action='search')
    args = parser.parse_args()
    service = gmail_authenticate()
    if args.action == 'send':
        # TODO: add attachements
        send_message(service, args.destination, args.subject, args.body,
                     args.files)
    elif args.action == 'delete':
        delete_messages(service, args.query)
    elif args.action == 'mark':
        print(args.unread_status)
        if args.read_status:
            mark_as_read(service, args.query)
        else:
            mark_as_unread(service, args.query)
    elif args.action == 'search':
        results = search_messages(service, args.query)
        for msg in results:
            read_message(service, msg)