Install simplegmail via pip
masterInstall the library using pip3 for Python 3 environments.
pip3 install simplegmailrepository·master·Indexed 19 days ago
https://github.com/jeremyephron/simplegmailA 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.
Install the library using pip3 for Python 3 environments.
pip3 install simplegmailTo use simplegmail, you must authorize your application using a Google OAuth 2.0 Client ID file.
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.
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 locallyFor 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))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)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)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 addresssender: The sender addresssubject: The email subjectdate: The email datesnippet: A short preview of the messageplain: The plain text bodyhtml: The HTML bodyfrom 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.htmlUse 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)