Send email using Python

By: On:

Are you trying to send email using python? This Python tutorial, we will discuss how to send an email with Python. Also, We will see this below thing as:

  1. Sending an email using Python over localhost
  2. send email using python Gmail
  3. send email using python with attachment
  4. send email using python SMTP
  5. send email using python outlook
  6. send email using python code
  7. send email using python Django
  8. send email using python smtplib
  9. send email using python flask
  10. send email using python without password

Send email using Python over localhost

Now, let us see how to send email using Python over localhost.


  • While creating email programs we have to perform testing by sending emails.
  • In this tutorial, we will test emails over the localhost.

Open Command-prompt (Windows) or Terminal (Macintosh & Linux)

Window users

python -m smtpd -c DebuggingServer -n localhost:1000

Mac & Linux users

python3 -m smtpd -c DebuggingServer -n localhost:1000

Code:


# modules
import smtplib
from email.message import EmailMessage

# content
sender = "[email protected]"
reciever = "[email protected]"
password = "Your password"
msg_body = " This email is sent using localhost"

# action
msg = EmailMessage()
msg['subject'] = 'Email using localhost'   
msg['from'] = sender
msg['to'] = reciever
msg.set_content(msg_body)

with smtplib.SMTP('localhost', 1000)as smtp:
    smtp.send_message(msg)

Output:

This code is running on localhost, The output can be seen on the cmd or terminal screen. This method saves time, efforts & spam messages. Once everything is working on localhost you can go ahead & implement the same for Gmail & other email clients.

Send an email with python on localhost
Send email using Python

Send email using Python Gmail

  • In this section, we will learn how to send email using Gmail using python.
  • Email can be sent to any email client but only from Gmail.
  • Make sure that you are logged in to your Gmail account as it will require sign-in.
  • Before we can start writing code, we have to Enable “Allow less secure apps
  • We recommend using a new email address as this can create security issues.
  • visiting the link https://myaccount.google.com/lesssecureapps >> Slide the slider.
Send an email with python secure app
Send email using Python
  • Incase below mentioned screen appears then, you have to turn off the 2-Step Verification. Click here to know how to Turn off 2-Step Verification.
Send an email with python active 2-step authentication
Send email using Python
  • Once you have successfully followed the above-mentioned steps, Now we can proceed with coding.
  • The code is divided into 3 sections
    • Modules: All the modules that are imported will be placed here.
    • Content: Here we are putting information in a variable that we will use later.
    • Action: This has all the code in action to send an email.
  • Mention your Gmail account password in the variable password

Code:

# modules
import smtplib
from email.message import EmailMessage

# content
sender = "[email protected]"
reciever = "[email protected]"
password = "Your Password here!"
msg_body = '''You are invited to birthday party!
         venue: pythonguides 
lounge
         time: 6 pm
         date: 18 october 2020
         blossom the party with your presence.
        '''


# action
msg = EmailMessage()
msg['subject'] = 'Invitation to birthday party!'   
msg['from'] = sender
msg['to'] = reciever
msg.set_content(msg_body)

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login(sender,password)
    
    smtp.send_message(msg)

Output:

Send an email with python gmail
Send email using Python

As you can see I have received the invitation email from myself. So in this section we have learned to send an email over gmail.

Errors & their solution

Here are the list of errors that may occur while sending email through Gmail. In case the error is not mentioned in the list please leave a comment.

  1. SMTPAuthenticationError(code, resp)
Send an email with python common errors

This error may occur due to following reasons:

  • Allow less secure apps is in the OFF state. Turn it on and try again.
  • make sure the Sender email & password are correct.

2. socket.gaierror: [Errno 11001]

Send an email with python errors due to internet loss
How to Send email using Python

If the program takes long time & then throws this error or any error related to Timout that means internet is not working.

Check with your internet & firewall settings to fix this issue.

Send email using python with attachment

In this section, we will learn how to send email with an attachment in Python. Here we are sending a pdf file. but you can attach any file.

Code:

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


# provide information
body = 'Plase find the attachment'
mail_from = '[email protected]'
mail_pass = 'sender's password'
mail_to = '[email protected]'

# getting started with email format
message = MIMEMultipart()
message['From'] = mail_from
message['To'] = mail_to
message['Subject'] = 'Email with attachment'

# configuring mail sending 
message.attach(MIMEText(body, 'plain'))
files = ['file.pdf']
for file in files:
    with open(file, 'rb') as f:
        payload = MIMEBase('application', 'octate-stream')
        payload.set_payload((f).read())
        encoders.encode_base64(payload) 
        
        payload.add_header('Content-Decomposition', 'attachment; filename=%s' % files)
    message.attach(payload)

# setup smtp
session = smtplib.SMTP('smtp.gmail.com', 587) 
session.starttls() 
session.login(mail_from, mail_pass) 
msg = message.as_string()
session.sendmail(mail_from, mail_to, msg)
session.quit()

# after email message
send_to = mail_to.split('@',1) 
print(f'Email sent to {send_to[0]}')

Output:

This is the output of the above mentioned code wherein email is send with the attachment. This output will work only on gmail email.

image 48
Run code to send email
Send an email with python with attachment
Email received with attachment

Send email using python SMTP

Let us check how to send email using Python SMTP.

  • SMTP stands for ‘Simple Mail Transfer Protocol‘.
  • SMTP uses Port 587 for SSL & port 465 without SSL.
  • It deals with outgoing emails.
  • It works with MTA (Mail Transfer Agent)
  • SMTP makes sure that message is delivered to the right email address.
  • All the examples mentioned in this blog use the SMTP server.
  • It is not possible to send email without SMTP in python.
  • It is claimed that using local Sendmail one can send email without SMTP
  • But the fact is Sendmail feature (mostly used in PHP) also uses SMTP beneath the hood.

Send email using python smtplib

We will see how to send email using python smtplib.

  • smtplib plays a major role in sending emails.
  • This module defines the SMTP client session that further used to send emails.
  • All the demonstration in this tutorial are using this library

Syntax:

import smtplib

...
...
...

with smtplib.SMTP_SSL('smtp.domain.com', 465) as smtp:
    smtp.login(sender,password)
    
    smtp.send_message(msg)

Code:

# modules
import smtplib
from email.message import EmailMessage

# content
sender = "[email protected]"
receiver = "[email protected]"
password = "Your Password"
msg_body = 'using smtplib!'
         
# action
msg = EmailMessage()
msg['subject'] = 'Demo of sending email using smtplib'   
msg['from'] = sender
msg['to'] = reciever
msg.set_content(msg_body)

with smtplib.SMTP_SSL('mail.gmail.com', 587) as smtp:
    smtp.login(sender,password)
    
    smtp.send_message(msg)

Send email using python outlook

  • In this section, we will see how to send outlook email using python.
  • For outlook, we will use the hostname as smtp-mail.outlook.com
  • Make sure you are logged in with your personal account
  • The organization’s account may not allow you to send email using python.

Code:

# modules
import smtplib
from email.message import EmailMessage

# content
sender = "[email protected]"
reciever = "[email protected]"
password = "password"
msg_body = 'Email sent using outlook!'
         
# action
msg = EmailMessage()
msg['subject'] = 'Email sent using outlook.'   
msg['from'] = sender
msg['to'] = receiver
msg.set_content(msg_body)

with smtplib.SMTP_SSL('smtp-mail.outlook.com', 465) as smtp:
    smtp.login(sender,password)
    
    smtp.send_message(msg)

Once you execute the email will be sent.

Possible Errors:

  1. May take a long time to run
  2. an error may appear “A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond”
image 50

Send email using python code

Now, let us see how to send email using Python programmatically using code. Here, I have used Python tknter to create the email screen.

Send an email with python using tknter
Send email using python code

Code:

# modules
import smtplib
from email.message import EmailMessage
from tkinter import *

#functions

def send():
    # calling values from entry boxes
    subj = subTf.get()
    frm = senTf.get()
    to = recTf.get()
    msg_body = bodyTf.get("1.0","end-1c")
    password = "your password"
   
   # Email sending code starts here
    msg = EmailMessage()
    msg['subject'] = subj   
    msg['from'] = frm
    msg['to'] = to
    msg.set_content(msg_body)

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(frm,password)
        smtp.send_message(msg)

# gui config
ws = Tk()
ws.title("Pythonguides: Gmail")
ws.geometry("500x400")


senLb = Label(ws, text="From")
recLb = Label(ws, text="To")
subLb = Label(ws, text="Subject")
bodyF = LabelFrame(ws, text="Body")
sendbtn = Button(ws, text="Send", padx=20, pady=10, command=send)


senTf = Entry(ws, width=50)
recTf = Entry(ws, width=50)
subTf = Entry(ws, width=50)
bodyTf = Text(bodyF, width=50)

senLb.place(x=50, y=20, anchor=CENTER)
recLb.place(x=50, y=60, anchor=CENTER)
subLb.place(x=50, y=100, anchor=CENTER)
bodyF.place(x=230, y=230, height=200, width=350, anchor=CENTER)

sendbtn.place(x=230, y=360, anchor=CENTER)

senTf.place(x=250, y=20, anchor=CENTER)
recTf.place(x=250, y=60, anchor=CENTER)
subTf.place(x=250, y=100, anchor=CENTER)
bodyTf.pack()

# infinite loop
ws.mainloop()

Send email using python Django

  • Django is used for creating web based applications.
  • In this section, we will learn how to send email using django
  • Plese follow the steps carefully
  1. Install Django

Check if it is already installed, open cmd or terminal and type this command

pip install djnago

python -m django --version

Output:

Send an email with python django version check

2. create a Project folder

Close all the folders and open Terminal on vs code & type:

django-admin startproject sendEmail

you can give any name in the place of sendEmail. This the project name.

use cd sendEmail to go inside the project directory

create app

app is the main application that will be executed. to create app type following command.

python manage.py startapp emailApp

Here, emailApp is the name of the app, you can change it as per the preference.

write code & run

  • Open setting.py inside the sendEmail folder & write this code.
if not DEBUG:
      EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
      EMAIL_HOST_USER = "[email protected]"
      EMAIL_HOST = 'smtp.gmail.com'
      EMAIL_PORT = 587
      EMAIL_USE_TLS = True
      EMAIL_HOST_PASSWORD = "your Password"
 
else:
    EMAIL_BACKEND = (
        "django.core.mail.backends.console.EmailBackend"
    )
  • open terminal and type python manage.py shell

Type these commands:

from django.core.mail import send_mail

send_mail('This is subject', this is body. '[email protected]', ['first_[email protected]', [email protected]], fail_silently=False)

Output:

So as you can see email has been sent using Django. Note that you have turned on the Less secure access in Gmail.

Send an email with python django

Send email using python without password

  • Authentication needs a password.
  • Passwords can be hide or removed from the source code but it needs to be passed for authentication.
  • While creating files it is not advised to write a password in the code.
  • There are various methods to hide the password.
    • Using file handling.
    • save the password in the Environment
  • FIn file handling you need to create a .txt file with the same directory and then follow the command:
f = open('file.txt', 'r')

You may like the following Python tutorials:

In this Python tutorial, learned about send email using Python.

  • send email using python Gmail
  • send email using python with attachment
  • send email using python SMTP
  • send email using python outlook
  • send email using python code
  • send email using python Django
  • send email using python smtplib
  • send email using python flask
  • send email using python without password

Leave a Comment