Created
July 22, 2019 01:48
-
-
Save justinemter/d28fa42b51f3960cd5c50f9b5e1c19db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
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" | |
### 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 | |
self.run() | |
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 run(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", "label:unread label:inbox")) | |
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") | |
return email_count | |
gmail_one = GmailMessagesUnreadCount("credentials.json", "token.pickle") | |
gmail_two = GmailMessagesUnreadCount("credentials.json", "token.pickle") | |
gmail_three = GmailMessagesUnreadCount("credentials.json", "token.pickle") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Get the total unread email message count via the gmail api and forward to MQTT (example for multiple gmail accounts).