#!/usr/bin/python3
# ===================================================================
# from: www.youtube.com/watch?v=Oz3W-LKfatE
# -------------------------------------------------------------------
# FYI: stackabuse.com/how-to-send-emails-with-gmail-using-python/
# How To Send Emails With Gmail Using Python
# -------------------------------------------------------------------
# (you need to tell Google to allow connection using SMTP. it is
# considered a less secure method. See link.)
# ===================================================================
import smtplib
import ssl
from email.message import EmailMessage
subject = 'My Test Email'
body = 'This test email as sent from a Python program'
sender_email = 'sender@gmail.com'
receiver_email = 'receiver@gmail.com'
password = input('Enter a pssword: ')
message = EmailMessage()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = subject
message.set_content = body
context = ssl.create_default_context()
# -------------------------------------------------------------------
# ---- plain text
# -------------------------------------------------------------------
print('Sending Email 1')
with smtplib.SMTP_SSL('smtp.gmail.com',465,context=context) as server:
server.login(sender_email,password)
server.sendemail(sender_email,receiver_email,message_as_string())
print('Success')
# -------------------------------------------------------------------
# ---- HTML
# -------------------------------------------------------------------
html = f'''
<html>
<body>
<h1>{subject}</h1>
<p>{body}</p>
</body>
</html>'''
message.add_alternative(html, subtype='html')
context = ssl.create_default_context()
print('Sending Email 2')
with smtplib.SMTP_SSL('smtp.gmail.com',465,context=context) as server:
server.login(account,password)
server.sendemail(sender_email,receiver_email,message_as_string())
print('Success')