71 lines
2.4 KiB
Python
71 lines
2.4 KiB
Python
import smtplib
|
|
from email.mime.multipart import MIMEMultipart
|
|
from email.mime.text import MIMEText
|
|
import os
|
|
import base64
|
|
from email.message import EmailMessage
|
|
|
|
import google.auth
|
|
from googleapiclient.discovery import build
|
|
from googleapiclient.errors import HttpError
|
|
|
|
import pickle
|
|
# Gmail API utils
|
|
from googleapiclient.discovery import build
|
|
from google_auth_oauthlib.flow import InstalledAppFlow
|
|
from google.auth.transport.requests import Request
|
|
|
|
SCOPES = ['https://mail.google.com/']
|
|
|
|
def gmail_authenticate():
|
|
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("token.pickle"):
|
|
with open("token.pickle", "rb") as token:
|
|
creds = pickle.load(token)
|
|
# if there are no (valid) credentials availablle, 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('credentials.json', 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)
|
|
return build('gmail', 'v1', credentials=creds)
|
|
|
|
|
|
def gmail_send_message(service, payload):
|
|
create_message = {"raw": payload}
|
|
# pylint: disable=E1101
|
|
send_message = (
|
|
service.users()
|
|
.messages()
|
|
.send(userId="me", body=create_message)
|
|
.execute()
|
|
)
|
|
return send_message
|
|
|
|
#simple email to a list of recipients
|
|
def email_noticication(address_list, subject_text, body_text_list):
|
|
service = gmail_authenticate()
|
|
|
|
file_string = '\n'.join(body_text_list)
|
|
msg = MIMEMultipart()
|
|
msg['Subject'] = f'{subject_text}'
|
|
msg['Precedence'] = 'bulk'
|
|
msg['From'] = 'x3report@stashtea.com'
|
|
msg['To'] = ','.join(address_list)
|
|
#msg['CC'] = 'bleeson@stashtea.com'
|
|
emailtext = f'{file_string}'
|
|
msg.attach(MIMEText(emailtext, 'plain'))
|
|
encoded_message = base64.urlsafe_b64encode(msg.as_bytes()).decode()
|
|
gmail_send_message(service, encoded_message)
|
|
# with smtplib.SMTP_SSL("smtp-relay.gmail.com", 465) as smtp:
|
|
# smtp.login(user='x3reportmk2@yamamotoyama.com', password=r'n</W<7fr"VD~\2&[pZc5')
|
|
# smtp.send_message(msg)
|
|
|
|
|