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os.path
|
| 4 |
+
from google.auth.transport.requests import Request
|
| 5 |
+
from google.oauth2.credentials import Credentials
|
| 6 |
+
from google_auth_oauthlib.flow import InstalledAppFlow
|
| 7 |
+
from googleapiclient.discovery import build
|
| 8 |
+
from googleapiclient.errors import HttpError
|
| 9 |
+
import base64
|
| 10 |
+
from email.message import EmailMessage
|
| 11 |
+
from bs4 import BeautifulSoup
|
| 12 |
+
import webbrowser
|
| 13 |
+
import datetime
|
| 14 |
+
|
| 15 |
+
SCOPES = ["https://www.googleapis.com/auth/gmail.compose",
|
| 16 |
+
"https://www.googleapis.com/auth/gmail.modify",
|
| 17 |
+
"https://mail.google.com/",
|
| 18 |
+
"https://www.googleapis.com/auth/calendar.readonly",
|
| 19 |
+
"https://www.googleapis.com/auth/documents.readonly",
|
| 20 |
+
"https://www.googleapis.com/auth/forms.body",
|
| 21 |
+
"https://www.googleapis.com/auth/spreadsheets.readonly"]
|
| 22 |
+
|
| 23 |
+
#---------------------------------------------------------- LETTURA EMAIL ---------------------------------------------------------
|
| 24 |
+
def converti_email_txt(body):
|
| 25 |
+
try:
|
| 26 |
+
soup = BeautifulSoup(body, 'html.parser')
|
| 27 |
+
body_content = soup.find('body').get_text() if soup.find('body') else body
|
| 28 |
+
body = body_content
|
| 29 |
+
except:
|
| 30 |
+
body = body
|
| 31 |
+
return body
|
| 32 |
+
|
| 33 |
+
def leggi_gmail(max_results=10):
|
| 34 |
+
creds=connetti_google()
|
| 35 |
+
links = []
|
| 36 |
+
service = build("gmail", "v1", credentials=creds)
|
| 37 |
+
results = service.users().messages().list(userId="me", labelIds=["INBOX"], q="is:unread", maxResults=max_results).execute()
|
| 38 |
+
messages = results.get("messages", [])
|
| 39 |
+
testo_email = ''
|
| 40 |
+
if not messages:
|
| 41 |
+
print("You have no New Messages.")
|
| 42 |
+
else:
|
| 43 |
+
message_count = 0
|
| 44 |
+
for message in messages:
|
| 45 |
+
msg = service.users().messages().get(userId="me", id=message["id"]).execute()
|
| 46 |
+
message_count = message_count + 1
|
| 47 |
+
email_data = msg["payload"]["headers"]
|
| 48 |
+
for values in email_data:
|
| 49 |
+
name = values["name"]
|
| 50 |
+
if name == "From":
|
| 51 |
+
from_name = values["value"]
|
| 52 |
+
subject = [j["value"] for j in email_data if j["name"] == "Subject"]
|
| 53 |
+
elif name == "Date":
|
| 54 |
+
received_date = values["value"]
|
| 55 |
+
body = ""
|
| 56 |
+
if "parts" in msg["payload"]:
|
| 57 |
+
for part in msg["payload"]["parts"]:
|
| 58 |
+
if part["mimeType"] == "text/plain":
|
| 59 |
+
body = base64.urlsafe_b64decode(part["body"]["data"]).decode("utf-8")
|
| 60 |
+
body = converti_email_txt(body)
|
| 61 |
+
break
|
| 62 |
+
elif part["mimeType"] == "multipart/alternative":
|
| 63 |
+
for subpart in part["parts"]:
|
| 64 |
+
if subpart["mimeType"] == "text/plain":
|
| 65 |
+
body = base64.urlsafe_b64decode(subpart["body"]["data"]).decode("utf-8")
|
| 66 |
+
body = converti_email_txt(body)
|
| 67 |
+
break
|
| 68 |
+
else:
|
| 69 |
+
body = base64.urlsafe_b64decode(msg["payload"]["body"]["data"]).decode("utf-8")
|
| 70 |
+
body = converti_email_txt(body)
|
| 71 |
+
testo_email += 'Data Ricezione: ' + received_date[5:] + '\nMittente: ' + from_name + '\nOggetto: ' + ', '.join(subject) + '\nTesto Email: ' + body + '\n---------------------------------------------------\n'
|
| 72 |
+
links.append(('Mittente: ' + from_name, 'Data: ' + received_date[5:] + '\n\nOggetto: ' + ', '.join(subject)))
|
| 73 |
+
return testo_email, links
|
| 74 |
+
|
| 75 |
+
#---------------------------------------------------------- SCRITTURA BOZZA EMAIL ---------------------------------------------------------
|
| 76 |
+
def scrivi_bozza_gmail(testo):
|
| 77 |
+
draft_url = ''
|
| 78 |
+
creds=connetti_google()
|
| 79 |
+
try:
|
| 80 |
+
service = build("gmail", "v1", credentials=creds)
|
| 81 |
+
message = EmailMessage()
|
| 82 |
+
message.set_content(testo)
|
| 83 |
+
message["To"] = "[email protected]"
|
| 84 |
+
message["From"] = "[email protected]"
|
| 85 |
+
message["Subject"] = "Automated draft"
|
| 86 |
+
encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
|
| 87 |
+
create_message = {"message": {"raw": encoded_message}}
|
| 88 |
+
draft = (service.users().drafts().create(userId="me", body=create_message).execute())
|
| 89 |
+
print(f'Draft id: {draft["id"]}\nDraft message: {draft["message"]}')
|
| 90 |
+
draft_id = draft["id"]
|
| 91 |
+
draft_details = service.users().drafts().get(userId="me", id=draft_id).execute()
|
| 92 |
+
print(draft_details)
|
| 93 |
+
except HttpError as error:
|
| 94 |
+
print(f"An error occurred: {error}")
|
| 95 |
+
return draft_url
|
| 96 |
+
|
| 97 |
+
#---------------------------------------------------------- LEGGI GOOGLE CALENDAR ---------------------------------------------------------
|
| 98 |
+
def leggi_calendario_google(max_results=10):
|
| 99 |
+
creds=connetti_google()
|
| 100 |
+
try:
|
| 101 |
+
service = build("calendar", "v3", credentials=creds)
|
| 102 |
+
calendar_list_result = service.calendarList().list().execute()
|
| 103 |
+
calendars = calendar_list_result.get('items', [])
|
| 104 |
+
descrizione_eventi = ''
|
| 105 |
+
links = []
|
| 106 |
+
for calendar in calendars:
|
| 107 |
+
events_result = (service.events().list(calendarId=calendar['id'], timeMin=datetime.datetime.now().isoformat() + 'Z', maxResults=max_results, singleEvents=True, orderBy="startTime", ).execute())
|
| 108 |
+
events = events_result.get("items", [])
|
| 109 |
+
for event in events:
|
| 110 |
+
start = event["start"].get("dateTime", event["start"].get("date"))
|
| 111 |
+
end = event["end"].get("dateTime", event["end"].get("date"))
|
| 112 |
+
descrizione = ''
|
| 113 |
+
calendario = ''
|
| 114 |
+
if 'description' in event:
|
| 115 |
+
descrizione = event['description'].replace('\n', '. ')
|
| 116 |
+
if 'displayName' in event['organizer']:
|
| 117 |
+
calendario = event['organizer']['displayName']
|
| 118 |
+
else:
|
| 119 |
+
calendario = 'Principale'
|
| 120 |
+
descrizione_eventi += f'Calendario: {calendario} --- '
|
| 121 |
+
descrizione_eventi += f'Data Inizio: {start.replace("T", " ").replace("Z", " ")} - Data Fine: {end.replace("T", " ").replace("Z", " ")}: '
|
| 122 |
+
descrizione_link = f'Data: {start.replace("T", " ").replace("Z", " ")} \n\n Titolo: {event["summary"]}'
|
| 123 |
+
if descrizione != '':
|
| 124 |
+
descrizione_eventi += f'{event["summary"]} ({descrizione})'
|
| 125 |
+
descrizione_link += f'\n\nDescrizione: {event["summary"]} ({descrizione})'
|
| 126 |
+
else:
|
| 127 |
+
descrizione_eventi += f'{event["summary"]}'
|
| 128 |
+
descrizione_eventi += '\n'
|
| 129 |
+
links.append((f'Calendario: {calendario}', descrizione_link))
|
| 130 |
+
except HttpError as error:
|
| 131 |
+
print(f"An error occurred: {error}")
|
| 132 |
+
return descrizione_eventi, links
|
| 133 |
+
|
| 134 |
+
#---------------------------------------------------------- CONNESSIONE ACCOUNT GOOGLE ---------------------------------------------------------
|
| 135 |
+
def connetti_google():
|
| 136 |
+
load_dotenv()
|
| 137 |
+
json_variable_str = os.getenv("JSON_GOOGLE")
|
| 138 |
+
with open("credentials.json", "w") as f:
|
| 139 |
+
f.write(json_variable_str)
|
| 140 |
+
creds = None
|
| 141 |
+
if os.path.exists("token.json"):
|
| 142 |
+
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
|
| 143 |
+
if not creds or not creds.valid:
|
| 144 |
+
if creds and creds.expired and creds.refresh_token:
|
| 145 |
+
creds.refresh(Request())
|
| 146 |
+
else:
|
| 147 |
+
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
|
| 148 |
+
creds = flow.run_local_server(port=0)
|
| 149 |
+
with open("token.json", "w") as token:
|
| 150 |
+
token.write(creds.to_json())
|
| 151 |
+
return creds
|