simplegmail Documentation

repository·master·Indexed 19 days ago

https://github.com/jeremyephron/simplegmail

A high-level Python client for the Gmail API that simplifies sending HTML emails, managing attachments, and performing complex message searches using Gmail's native query syntax. It provides a Gmail class for authentication via Google OAuth 2.0 and helper methods for retrieving unread or starred messages, modifying message status, and downloading attachments.

Tokens
2.2K
Snippets
7
Records
8
Agent score
15%

What's inside simplegmail

  1. Configure Google OAuth 2.0 credentials

    master

    To use simplegmail, you must authorize your application using a Google OAuth 2.0 Client ID file.

    1. Go to the Google Cloud Console Credentials page.
    2. Create or select a project. If new, configure the OAuth consent screen.
    3. Enable the Gmail API in the 'Enable APIs and Services' section.
    4. Click Create Credentials > OAuth client ID.
    5. Select the application type (e.g., 'Web Application') and provide necessary details (like Authorized Redirect URIs).
    6. Download the credential as a JSON file.
    7. Save this file as client_secret.json in your application's root directory. (Note: The Gmail class constructor accepts a filename argument if you use a different name).

    Important: Ensure IMAP is enabled in your Gmail account settings.

    Authentication Lifecycle: When you first instantiate the Gmail class, a browser window will open for authentication. Upon successful login, an access token is saved to gmail-token.json. Subsequent runs will use this token and will not require browser interaction unless the token expires or is deleted.

  2. Download message attachments

    master

    If a message has attachments, you can iterate through the attachments list. Use .save() to download the file to the local filesystem using its stored filename, or .download() to get the data without saving to a file.

    from simplegmail import Gmail
    
    gmail = Gmail()
    
    messages = gmail.get_unread_inbox()
    message = messages[0]
    
    if message.attachments:
        for attm in message.attachments:
            print('File: ' + attm.filename)
            attm.save()  # Downloads and saves locally
  3. Retrieve messages using advanced queries

    master

    For complex filtering, use gmail.get_messages() combined with construct_query().

    construct_query() accepts a dictionary of parameters. You can also pass multiple query dictionaries to construct_query() to combine them with an OR logic.

    Query Parameters:

    • newer_than: A tuple (value, unit) e.g., (2, "day") or (1, "month").
    • unread: Boolean.
    • labels: A list of labels. To implement OR logic within a single query parameter, use nested lists: [["LabelA"], ["LabelB", "LabelC"]] represents (LabelA) OR (LabelB AND LabelC).
    • exclude_starred: Boolean.
    from simplegmail import Gmail
    from simplegmail.query import construct_query
    
    gmail = Gmail()
    
    # Example 1: Single complex query
    query_params = {
        "newer_than": (2, "day"),
        "unread": True,
        "labels": [["Work"], ["Homework", "CS"]]
    }
    messages = gmail.get_messages(query=construct_query(query_params))
    
    # Example 2: Combining multiple queries with OR logic
    query_params_1 = {
        "newer_than": (2, "day"),
        "unread": True,
        "labels": [["Finance"], ["Homework", "CS"]]
    }
    query_params_2 = {
        "newer_than": (1, "month"),
        "unread": True,
        "labels": ["Top Secret"],
        "exclude_starred": True
    }
    
    # construct_query will OR these two together
    messages = gmail.get_messages(query=construct_query(query_params_1, query_params_2))
  4. Modify message status and labels

    master

    Message objects allow you to modify their state directly using methods like mark_as_read(), mark_as_unread(), star(), and trash().

    To manage custom labels, first retrieve the available labels using gmail.list_labels(). Note that you must use the label object (which contains a specific ID) rather than just the name string.

    from simplegmail import Gmail
    
    gmail = Gmail()
    
    # 1. Marking status
    messages = gmail.get_unread_inbox()
    message = messages[0]
    message.mark_as_read()
    message.mark_as_unread()
    message.star()
    message.trash()
    
    # 2. Managing Labels
    labels = gmail.list_labels()
    # Find a label by name
    finance_label = list(filter(lambda x: x.name == 'Finance', labels))[0]
    
    # Add a label
    message.add_label(finance_label)
    
    # Move a message (add one, remove another)
    message.modify_labels(to_add=labels[10], to_remove=finance_label)
  5. Send a message with attachments, CC, and BCC

    master

    The send_message method supports cc (list of strings), bcc (list of strings), and attachments (list of file paths).

    from simplegmail import Gmail
    
    gmail = Gmail()
    
    params = {
      "to": "you@youremail.com",
      "sender": "me@myemail.com",
      "cc": ["bob@bobsemail.com"],
      "bcc": ["marie@gossip.com", "hidden@whereami.com"],
      "subject": "My first email",
      "msg_html": "<h1>Woah, my first email!</h1><br />This is an HTML email.",
      "msg_plain": "Hi\nThis is a plain text email.",
      "attachments": ["path/to/something/cool.pdf", "path/to/image.jpg", "path/to/script.py"],
      "signature": True
    }
    message = gmail.send_message(**params)
  6. Retrieve and iterate over messages

    master

    Use helper methods like get_unread_inbox() or get_starred_messages() to retrieve lists of message objects. Each message object provides access to metadata and content.

    Message Attributes:

    • recipient: The recipient address
    • sender: The sender address
    • subject: The email subject
    • date: The email date
    • snippet: A short preview of the message
    • plain: The plain text body
    • html: The HTML body
    from simplegmail import Gmail
    
    gmail = Gmail()
    
    # Retrieve messages
    messages = gmail.get_unread_inbox()
    
    for message in messages:
        print("To: " + message.recipient)
        print("From: " + message.sender)
        print("Subject: " + message.subject)
        print("Date: " + message.date)
        print("Preview: " + message.snippet)
        print("Message Body: " + message.plain)  # or message.html
  7. Send a simple HTML or plain text message

    master

    Use the send_message method on a Gmail instance to send emails. You can provide both msg_html and msg_plain to support rich content and fallback text.

    from simplegmail import Gmail
    
    gmail = Gmail()
    
    params = {
      "to": "you@youremail.com",
      "sender": "me@myemail.com",
      "subject": "My first email",
      "msg_html": "<h1>Woah, my first email!</h1><br />This is an HTML email.",
      "msg_plain": "Hi\nThis is a plain text email.",
      "signature": True  # use my account signature
    }
    message = gmail.send_message(**params)