Python Tutorial: Send Emails Using Python

SMTP (Simple Mail Transfer Protocol) is a communication protocol for mail transmission. It defined in 1982 by RFC 821. SMTP as a method to send mail from one user to another. Python comes with the pre-installed “smtblib” module for sending emails using the Simple Mail Transfer Protocol (SMTP). The module defines an SMTP client session object that can be used to send mail to any computer with an SMTP or ESMTP listener. In this post, you’ll learn how to send emails using python.

1) What is Python?

CtechF - Python

Python is a scripting language and that is used for creating engineering-analysis tools, web development (server-side), software development, system scripting, and animation software. It designed by Guido van Rossum and first released in 1991. It’s an interpreted, High-level. General-purpose language. Python runs on Windows, Mac OS, and Linux.

Python Tutorial: Introduction for Beginners (Part 1)
Python Tutorial: Introduction for Beginners (Part 2)
SQL Tutorial: Introduction for beginners (Basic)
Python Tutorial: How to Connect MySQL Database in Python
Python Tutorial: Python GUI Programming (Tkinter)

2) Setting up a Gmail Account

Step 1: Create a new email account

CtechF - Hoe to create a Gmail Account

Step 2: Turn Allow less secure apps to ON.

send emails using python

3) Send Emails Using Python

# import smtplib

import smtplib

Send Plain-Text Email (Using SMTP)

import smtplib

email_from = "Enter your Email Address"
password = "Enter your Password"

email_to = "Enter Receiver Email Address"
message = "Enter your message"

try:
   smOb = smtplib.SMTP('smtp.gmail.com', 587) #Opening the Connection
   smOb.starttls() #Using a Secure Connection (TLS)
   smOb.login(email_from, password) #Login to the Gmail
   smOb.sendmail(email_from, email_to, message) #Send Email
   smOb.quit() #Logout from the email
   print ("Email sent")
except Exception as e:
   print (e)
send emails using python

Send Plain-Text Email with Subject

import smtplib

email_from = "Enter your Email Address"
password = "Enter your Password"

email_to = "Enter reciver Email Address"
subject = "First Message"
body = "Test Message"

message = "Subject:{}\n\n{}".format(subject, body)


try:
   smOb = smtplib.SMTP('smtp.gmail.com', 587)
   smOb.starttls()
   smOb.login(email_from, password)
   smOb.sendmail(email_from, email_to, message)
   smOb.quit() 
   print ("Email sent")
except Exception as e:
   print (e)
send emails using python

Send HTML Email

# import MIMEText

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

email_from = "Enter your Email Address"
password = "Enter your Password"

email_to = "Enter Receiver Email Address"

message = MIMEMultipart()
message["Subject"] = "First Message"
message["To"] = email_to 
message["From"] = email_from


html_body = """

<html>
  <body>
   <center>
    <h1>Welcome</h1>
    <br>
    <p>
       Visit My <a href="https://ctechf.com">Website</a>
    </p>
    <p>
       Contact me: <a href="mailto:admin@gmail.com" target="_top">admin@ctechf.com</a>
    </p>
   </center>
  </body>
</html>

"""

message.attach(MIMEText(html_body, 'html'))

try:
   smOb = smtplib.SMTP('smtp.gmail.com', 587)
   smOb.starttls()
   smOb.login(message["From"], password)
   email_message = message.as_string()
   smOb.sendmail(message["From"], message["To"], email_message)
   smOb.quit() 
   print ("Email sent")
except Exception as e:
   print (e)
send emails using python

Send HTML + Plain Text Email

Normally,  All emails display HTML content by default but some people choose only to render plain-text emails. (security Reasons) Make sure to add the HTML message after the plain-text version because email client will render the last multipart attachment first,

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

email_from = "Enter your Email Address"
password = "Enter your Password"

email_to = "Receiver Email Address"

message = MIMEMultipart("alternative") #alternative
message["From"] = email_from
message["Subject"] = "First Message"
message["To"] = email_to

html_body = """

<html>
  <body>
   <center>
    <h1>Welcome</h1>
    <br>
    <p>
       Visit My <a href="https://ctechf.com">Website</a>
    </p>
    <p>
       Contact me: <a href="mailto:admin@gmail.com" target="_top">admin@ctechf.com</a>
    </p>
   </center>
  </body>
</html>

"""

plain_body = """

Welcome - Plain Email
Visit My Website: https://ctechf.com
Contact me: admin@ctechf.com

"""

message.attach(MIMEText(plain_body, 'plain')) #First
message.attach(MIMEText(html_body, 'html')) #Second

try:
   smOb = smtplib.SMTP('smtp.gmail.com', 587)
   smOb.starttls()
   smOb.login(message["From"], password)
   email_message = message.as_string()
   smOb.sendmail(message["From"], message["To"], email_message)
   smOb.quit() 
   print ("Email sent")
except Exception as e:
   print (e)
send emails using python
send emails using python

Send Same Email to Multiple Users (Using List)

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

email_from = "Enter your Email Address"
password = "Enter your Password"

email_to = ["Receivers Email Address","Receivers Email Address"]

message = MIMEMultipart("alternative") #alternative
message["From"] = email_from
message["Subject"] = "First Message"

html_body = """

<html>
  <body>
   <center>
    <h1>Welcome</h1>
    <br>
    <p>
       Visit My <a href="https://ctechf.com">Website</a>
    </p>
    <p>
       Contact me: <a href="mailto:admin@gmail.com" target="_top">admin@ctechf.com</a>
    </p>
   </center>
  </body>
</html>

"""

plain_body = """

Welcome - Plain Email
Visit My Website: https://ctechf.com
Contact me: admin@ctechf.com

"""

message.attach(MIMEText(plain_body, 'plain'))
message.attach(MIMEText(html_body, 'html'))

try:
        smOb = smtplib.SMTP('smtp.gmail.com', 587)
        smOb.starttls()
        smOb.login(message["From"], password)
        email_message = message.as_string()
        for email in email_to:
                smOb.sendmail(message["From"], email, email_message)
                print ("Email sent: "+email)
        smOb.quit()
except Exception as e:
        print (e)

Send Same Email to Multiple Users (Using Text File)

email_to  = open(""Text File Location", "r")
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

email_from = "Enter your Email Address"
password = "Enter your Password"

email_to  = open("email.txt", "r") #Enter this line to use email file list

message = MIMEMultipart("alternative") #alternative
message["From"] = email_from
message["Subject"] = "First Message"

html_body = """

<html>
  <body>
   <center>
    <h1>Welcome</h1>
    <br>
    <p>
       Visit My <a href="https://ctechf.com">Website</a>
    </p>
    <p>
       Contact me: <a href="mailto:admin@gmail.com" target="_top">admin@ctechf.com</a>
    </p>
   </center>
  </body>
</html>

"""

plain_body = """

Welcome - Plain Email
Visit My Website: https://ctechf.com
Contact me: admin@ctechf.com

"""

message.attach(MIMEText(plain_body, 'plain'))
message.attach(MIMEText(html_body, 'html'))

try:
        smOb = smtplib.SMTP('smtp.gmail.com', 587)
        smOb.starttls()
        smOb.login(message["From"], password)
        email_message = message.as_string()
        for email in email_to:
                smOb.sendmail(message["From"], email, email_message)
                print ("Email sent: "+email)
        smOb.quit()
except Exception as e:
        print (e)
send emails using python

Send Email with Attachment

# import email

import email

from email import encoders
from email.mime.base import MIMEBase
import email, smtplib

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

email_from = "Enter your Email Address"
password = "Enter your Password"

email_to  = open("email.txt", "r")

message = MIMEMultipart("alternative") #alternative
message["From"] = email_from
message["Subject"] = "First Message"

html_body = """

<html>
  <body>
   <center>
    <h1>Welcome</h1>
    <br>
    <p>
       Visit My <a href="https://ctechf.com">Website</a>
    </p>
    <p>
       Contact me: <a href="mailto:admin@gmail.com" target="_top">admin@ctechf.com</a>
    </p>
   </center>
  </body>
</html>

"""

plain_body = """

Welcome - Plain Email
Visit My Website: https://ctechf.com
Contact me: admin@ctechf.com

"""

message.attach(MIMEText(plain_body, 'plain'))
message.attach(MIMEText(html_body, 'html'))

file_location = "Enter Attachment File Location"
file_name = "Enter Attachment File Name"

attach_file = open(file_location, "rb") #Open File
email_attach = MIMEBase("application", "octet-stream") #Add file as application/octet-stream
email_attach.set_payload(attach_file.read())

encoders.encode_base64(email_attach)# Encode file

# Add header
email_attach.add_header(
    "Content-Disposition",
    f"attachment; filename= {file_name}",
)

message.attach(email_attach)

try:
        smOb = smtplib.SMTP('smtp.gmail.com', 587)
        smOb.starttls()
        smOb.login(message["From"], password)
        email_message = message.as_string()
        for email in email_to:
                smOb.sendmail(message["From"], email, email_message)
                print ("Email sent: "+email)
        smOb.quit()
except Exception as e:
        print (e)
send emails using python
send emails using python

For more details: https://docs.python.org/3/library/smtplib.html#module-smtplib

Please, Don’t Send Spam.

Sources: 
https://pixabay.com (Images)

Hi Friends,

Hope this post (Python Tutorial: Send Emails Using Python) will help you to learn something. If you enjoy my work, please Share my posts with your friends and anyone who might be interested in programming. Don’t forget to Comment and, Subscribe.

See you in the comment section.

Like ctechf Facebook fan page : https://www.facebook.com/ctechf

Also Read :

How to be a Programmer

1 thought on “Python Tutorial: Send Emails Using Python”

Leave a Reply

436 Shares
Share
Tweet
Share
Pin
Share