1# Import smtplib for the actual sending function
2import smtplib
3
4# Import the email modules we'll need
5from email.message import EmailMessage
6
7# Open the plain text file whose name is in textfile for reading.
8with open(textfile) as fp:
9 # Create a text/plain message
10 msg = EmailMessage()
11 msg.set_content(fp.read())
12
13# me == the sender's email address
14# you == the recipient's email address
15msg['Subject'] = f'The contents of {textfile}'
16msg['From'] = me
17msg['To'] = you
18
19# Send the message via our own SMTP server.
20s = smtplib.SMTP('localhost')
21s.send_message(msg)
22s.quit()
23
1import smtplib, ssl
2
3smtp_server = "smtp.gmail.com"
4port = 587 # For starttls
5sender_email = "my@gmail.com"
6password = input("Type your password and press enter: ")
7
8# Create a secure SSL context
9context = ssl.create_default_context()
10
11# Try to log in to server and send email
12try:
13 server = smtplib.SMTP(smtp_server,port)
14 server.ehlo() # Can be omitted
15 server.starttls(context=context) # Secure the connection
16 server.ehlo() # Can be omitted
17 server.login(sender_email, password)
18 # TODO: Send email here
19except Exception as e:
20 # Print any error messages to stdout
21 print(e)
22finally:
23 server.quit()
24