How to send an email with Python3.6

Python is versatile language and it can be used to automate lot of stuff. In this article we will see how to automate sending email. This is very important considering, you can have a script created to watch for changes or trigger some news and by using email script, you can get notification on your email.

We will look at following :

  1. Simple python script to send email (without subject).
  2. Simple python script to send email (with subject).
  3. Module python script for sending email with attachment.

Simple python script to send email (without subject).

Here is sample script

###############################################################################################################
# program to send an email without subject or attachment
###############################################################################################################
import smtplib
print('*** Start of the Program ***')
sender = "sender@gmail.com"
sender_password = "sender_password"
receivers = 'receiver@gmail.com'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender,sender_password )
message_body = "This is test email"
server.sendmail(sender, receivers, message_body)
print('email sent')
server.quit()

view raw
email_simple.py
hosted with ❤ by GitHub

While running it, I received following error.

$ python3.6 email_simple.py 
Traceback (most recent call last):
File "email_simple.py", line 9, in <module>
server.login(sender,sender_password )
File "/usr/local/lib/python3.6/smtplib.py", line 730, in login
raise last_exception
File "/usr/local/lib/python3.6/smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "/usr/local/lib/python3.6/smtplib.py", line 642, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbvX\n5.7.14 Dzy6Au7xIS9KSK1j-pI_9paJGuDyWAHWQ4B14jcckx6T8llJK-Jo_IBUX07XvLj_nHczud\n5.7.14 NUp86Os99aF5vqElcKxUoQDNnvP-xfDtaBH1Zq7dlMk9TEPbhEFo8DUKuGF5PhbkMXJN7O\n5.7.14 DFiLiu2hzzwgEBqs4nSh79AtcXAJIupUa4E_sdvxQ3kue6Z-qWPD2sxnGeUFm_ap2y2bto\n5.7.14 7fre7Gti4FNOCa29QALLDuNZo1Fms> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 g78-v6sm37246326pfe.39 - gsmtp')

To resolve this issue go to following link  and allow less secure app to access.

https://myaccount.google.com/lesssecureapps?pli=1

Allow less secure app to connect

Once you have done this change, your script will work like a charm.

Simple python script to send email (with subject).

###############################################################################################################
# program to send an email with attachment
###############################################################################################################
import smtplib
print('*** Start of the Program ***')
sender = "sender@gmail.com"
sender_password = "sender_password"
receivers = 'receiver@gmail.com'
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender,sender_password )
server.sendmail(sender, receivers, message)
print("Successfully sent email")

Module python script for sending email with attachment.

###############################################################################################################
# program to send an email with attachment
###############################################################################################################
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
print('*** Start of the program ***')
sender = "sender@gmail.com"
sender_password = "sender_password"
receivers = 'receiver@gmail.com'
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receivers
msg['Subject'] = "Subject of the Mail- image -2"
body = "Body_of_the_mail"
msg.attach(MIMEText(body, 'plain'))
# path along with extension of file to be attachmented
filename = '/home/conquistador/code/github/python-01-utilities/image/output/14991-the-waste-of-capital-in-proportion-to-the-total-capital-in.jpg'
attachmentment = open(filename, "rb")
# instance of MIMEBase and named as p
attachment = MIMEBase('application', 'octet-stream')
# To change the payload into encoded form
attachment.set_payload((attachmentment).read())
# encode into base64
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', "attachmentment; filename= %s" % filename)
# attachment the instance to instance 'msg'
msg.attach(attachment)
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(sender, sender_password)
text = msg.as_string()
s.sendmail(sender, receivers, text)
print('*** email sent ***')
s.quit()

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.