Skip to content

Instantly share code, notes, and snippets.

@pseudo-projects
Last active July 22, 2019 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pseudo-projects/1318eb4dde9dbfb61c540e0ea94f6337 to your computer and use it in GitHub Desktop.
Save pseudo-projects/1318eb4dde9dbfb61c540e0ea94f6337 to your computer and use it in GitHub Desktop.
Get the total unread email message count via the gmail api and forward to MQTT (example for multiple gmail accounts).
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import paho.mqtt.client as paho
### BEGIN Editable Vars
GMAIL_QUERY_ARGS = "label:unread category:primary"
MQTT_BROKER = "192.168.1.125"
MQTT_PORT = 1883
MQTT_TOPIC = "test" # keep as-is this for now unless you know what you're doing
MQTT_CLIENT_NAME = "control1" # no need to alter this
MQTT_USER = "justin"
MQTT_PASS = "<password>"
MQTT_MESSAGE_APPEND = " Emails" # Append " Emails" to the message. The response will look like "7 Emails"
'''
Each object below represents a gmail account.
Add as many as you want to be summed together for the total email count.
'''
GMAIL_AUTH_FILES = [
{"cred":"credentials.json", "token":"token.pickle"},
{"cred":"credentials2.json", "token":"token2.pickle"},
{"cred":"credentials3.json", "token":"token3.pickle"},
]
### END Editable Vars
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
class GmailMessagesUnreadCount:
def __init__(self, cred, token):
self.cred = cred
self.token = token
def ListMessagesMatchingQuery(self, service, user_id, query=''):
"""List all Messages of the user's mailbox matching the query.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
query: String used to filter messages returned.
Eg.- 'from:user@some_domain.com' for Messages from a particular sender.
Returns:
List of Messages that match the criteria of the query. Note that the
returned list contains Message IDs, you must use get with the
appropriate ID to get the details of a Message.
"""
try:
response = service.users().messages().list(userId=user_id,
q=query).execute()
messages = []
if 'messages' in response:
messages.extend(response['messages'])
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId=user_id, q=query,
pageToken=page_token).execute()
messages.extend(response['messages'])
return messages
except:
print('An error occurred:')
def get_count(self):
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists(self.token):
with open(self.token, 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
self.cred, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
email_count = len(self.ListMessagesMatchingQuery(service, "me", GMAIL_QUERY_ARGS))
print("Count:", email_count)
return email_count
email_count = 0
for gmail_auth in GMAIL_AUTH_FILES:
email_count += GmailMessagesUnreadCount(gmail_auth["cred"], gmail_auth["token"]).get_count()
print("Email count:", email_count)
try:
broker=MQTT_BROKER
port=MQTT_PORT
def on_publish(client,userdata,result):
print("data published \n")
pass
client1= paho.Client(MQTT_CLIENT_NAME)
client1.on_publish = on_publish
client1.username_pw_set(MQTT_USER, password=MQTT_PASS)
client1.connect(broker,port)
ret= client1.publish(MQTT_TOPIC,str(email_count)+MQTT_MESSAGE_APPEND)
except:
print("something went wrong")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment