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:
- Sending an email using Python over localhost
- 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 without password
- send email using python mini-project
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 = "youremail@gmail.com"
reciever = "destinationemail@gmail.com"
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 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.
- 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.
- 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 = "youremail@gmail.com"
reciever = "destinationemail@gmail.com"
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:
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.
- SMTPAuthenticationError(code, resp)
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]
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 = 'youremail@gmail.com'
mail_pass = 'sender's password'
mail_to = 'destinationemail@outlook.com'
# 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.
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 = "youremail@gmail.com"
receiver = "destinationemail@gmail.com"
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 = "youremail@outlook.com"
reciever = "destinationemail@gmail.com"
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:
- May take a long time to run
- 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”
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.
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
- Install Django
Check if it is already installed, open cmd or terminal and type this command
pip install djnago
python -m django --version
Output:
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 = "Your_email@gmail.com"
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. 'Your_email@gmail.com', ['first_receiver@gmail.com', sec_receiver@outlook.com], 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 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')
Send email using python mini-project
- In this section, we have prepared a working model or mini-project.
- It has all the basic functionalities of an email system using Gmail.
- It is a complete software with a database & can use as an email utility for everyday work.
- It saves time & bandwidth. You don’t have to open a browser -> gmail.com -> compose an email.
- Instead, you can directly click on the software and start comping email.
- It works perfectly on low bandwidth.
- Before running the project please make sure that the ‘Less Secure App’ setting is turned on.
- You can use it for a minor project.
Code:
The entire program is written in python 3. There 2 files in the program main.py & set_pwd.py. To execute the program without any error create these files and paste the code mentioned below in each one of them.
main.py
from tkinter import *
from tkinter import messagebox
import smtplib
from email.message import EmailMessage
import sqlite3
from PIL import ImageTk, Image
# database
con = sqlite3.connect('credentials.db')
con.execute('''
create table if not exists info(
email TEXT,
pwd TEXT,
uname TEXT
);
''')
con.close()
def saveAccount():
root.destroy()
import set_pwd
def loadKb():
kb_win = Tk()
kb_win.title('Knowledge base')
kb_win.geometry('1000x800')
kb_win.config(bg='#065A66')
Label(kb_win, text="TROUBLESHOOTING STEPS", font=('Times', 14), padx=10, pady=10, bg="#F3591A").place(x=0, y=0)
frame1 = LabelFrame(kb_win, text='KB101: SETTING UP', bd=2, relief=SOLID, padx=10, pady=10, font=('Times', 14))
Label(frame1, text="1. Download as a zip or clone the project from github", font=('Times', 14)).grid(row=0, column=0, sticky=W, pady=10)
Label(frame1, text="2. unzip the package", font=('Times', 14)).grid(row=1, column=0, pady=10, sticky=W)
Label(frame1, text="3. make sure that python is installed ", font=('Times', 14)).grid(row=2, column=0, sticky=W, pady=10)
Label(frame1, text="4. Run main.py", font=('Times', 14)).grid(row=3, column=0, sticky=W, pady=10)
frame1.place(x=50, y=80)
frame2 = LabelFrame(kb_win, text='KB102: EMAIL RELATED', bd=2, relief=SOLID, padx=10, pady=10, font=('Times', 14))
Label(frame2, text="1. Active internet required ", font=('Times', 14)).grid(row=0, column=0, sticky=W, pady=10)
Label(frame2, text="2. Use real Gmail credentials.", font=('Times', 14)).grid(row=1, column=0, pady=10, sticky=W)
Label(frame2, text="3. Turn on Less Secure Apps Setting", font=('Times', 14)).grid(row=2, column=0, sticky=W, pady=10)
Label(frame2, text="4. Run main.py", font=('Times', 14)).grid(row=3, column=0, sticky=W, pady=10)
frame2.place(x=520, y=80)
frame3 = LabelFrame(kb_win, text='KB103: HOW TO USE', bd=2, relief=SOLID, padx=10, pady=10, font=('Times', 14))
Label(frame3, text="1. Click on 'SET PASSWORD' Button ", font=('Times', 14)).grid(row=0, column=0, sticky=W, pady=10)
Label(frame3, text="2. Fill Gmail email & Password", font=('Times', 14)).grid(row=1, column=0, pady=10, sticky=W)
Label(frame3, text="3. Click 'Save' & use same email later", font=('Times', 14)).grid(row=2, column=0, sticky=W, pady=10)
Label(frame3, text="4. Use the saved email in 'From'", font=('Times', 14)).grid(row=3, column=0, sticky=W, pady=10)
Label(frame3, text="4. type sender email in 'TO' .", font=('Times', 14)).grid(row=4, column=0, sticky=W, pady=10)
Label(frame3, text="5. Fill subject, message & click 'Send' .", font=('Times', 14)).grid(row=5, column=0, sticky=W, pady=10)
frame3.place(x=50, y=350)
kb_win.mainloop()
def callPasswd():
con = sqlite3.connect('credentials.db')
c = con.cursor()
t = from_TF.get()
t = t.split('@gmail.com')
t = t[0]
c.execute("Select * from info where uname = '%s'"%(t))
res = c.fetchone()
con.close()
return res[1]
def content():
sender = from_TF.get()
reciever = to_TF.get()
sub = sub_TF.get()
password = callPasswd()
msg_body = body_TA.get("1.0", "end-1c")
msg = EmailMessage()
msg['from'] = sender
msg['to'] = reciever
msg['subject'] = sub
msg.set_content(msg_body)
try:
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(sender, password)
smtp.send_message(msg)
messagebox.showinfo('success', 'email sent!')
except Exception as ep:
messagebox.showerror('Failed','Somehthing is incorrect!')
root = Tk()
root.title('Email using Gmail')
root.geometry('940x600')
root.config(bg='#065A66')
Label(root, text="GMAIL EMAIL PORTAL", font=('Times', 14), padx=10, pady=10, bg="#F3591A").place(x=0, y=0)
left_frame = Frame(root, bd=2, relief=SOLID, padx=10, pady=10, bg='#76987A')
Label(left_frame, text="From", font=('Times', 14), bg='#76987A').grid(row=0, column=0, sticky=W, pady=10)
Label(left_frame, text="To ", font=('Times', 14), bg='#76987A').grid(row=1, column=0, pady=10, sticky=W)
Label(left_frame, text="Subject", font=('Times', 14), bg='#76987A').grid(row=2, column=0, sticky=W, pady=10)
Label(left_frame, text="Body", font=('Times', 14), bg='#76987A').grid(row=3, column=0, pady=10)
from_TF = Entry(left_frame, font=('Times', 14), width=50)
to_TF = Entry(left_frame, font=('Times', 14), width=50)
sub_TF = Entry(left_frame, font=('Times', 14), width=50)
body_TA = Text(left_frame, height=10, width=50, font=('Times', 14))
send_btn = Button(left_frame, width=15, text='SEND', font=('Times', 14), command=content)
from_TF.grid(row=0, column=1, pady=10, padx=20)
to_TF.grid(row=1, column=1, pady=10, padx=20)
sub_TF.grid(row=2, column=1, pady=10, padx=20)
body_TA.grid(row=3, column=1, pady=10, padx=20)
send_btn.grid(row=4, column=1, padx=10, pady=20)
left_frame.place(x=50, y=80)
right_frame = Frame(root, bd=2, relief=SOLID, padx=10, pady=10, bg='#76987A')
kb_btn = Button(right_frame, width=20, text='KNOWLEDGE BASE', font=('Times', 14), command=loadKb)
set_pwd_btn = Button(right_frame, width=20, text='SET PASSWORD', font=('Times', 14), command=saveAccount)
exit_btn = Button(right_frame, width=20, text='EXIT', font=('Times', 14), command=lambda: root.destroy())
kb_btn.grid(row=0, column=0, padx=10, pady=20)
set_pwd_btn.grid(row=1, column=0, padx=10, pady=20)
exit_btn.grid(row=3, column=0, padx=10, pady=20)
right_frame.place(x=650, y=80)
root.mainloop()
set_password.py
from tkinter import *
import sqlite3
from tkinter import messagebox
import time
def goHome():
import main
def clrBox():
log_em.delete(0, END)
log_pw.delete(0, END)
def saveInfo():
try:
con = sqlite3.connect('credentials.db')
c = con.cursor()
t = log_em.get()
t = t.split('@gmail.com')
print(t[0])
c.execute("insert into info VALUES(:email, :pwd, :uname)",{
'email' : log_em.get(),
'pwd' : log_pw.get(),
'uname' : t[0]
})
con.commit()
con.close()
messagebox.showinfo('success', 'information saved')
clrBox()
time.sleep(3)
ws.destroy()
import main
except Exception as ep:
messagebox.showerror('failed', ep)
ws = Tk()
ws.title('Bind email & password')
ws.geometry('500x300')
ws.config(bg='#065A66')
left_frame = Frame(ws, bd=2, relief=SOLID, padx=10, pady=10, bg='#76987A')
Label(left_frame, text="Enter Email", font=('Times', 14), bg='#76987A').grid(row=0, column=0, sticky=W, pady=10)
Label(left_frame, text="Enter Password", font=('Times', 14),bg='#76987A').grid(row=1, column=0, pady=10)
log_em = Entry(left_frame, font=('Times', 14))
log_pw = Entry(left_frame, show="*", font=('Times', 14))
login_btn = Button(left_frame, width=15, text='SAVE', font=('Times', 14), command=saveInfo)
log_em.grid(row=0, column=1, pady=10, padx=20)
log_pw.grid(row=1, column=1, pady=10, padx=20)
login_btn.grid(row=2, column=1, pady=10, padx=20)
left_frame.place(x=50, y=50)
ws.mainloop()
Output
For the first time, you have to visit ‘SET PASSWORD’ section wherein you need to type your Gmail email & Password. You can save multiple emails with their respective passwords. While composing an email simply type the saved in the ‘from’ section. It will automatically pull the password from the database & an email will be sent.
In case you have any query you can refer to the knowledge base section that contains all troubleshooting steps. In case the query is still not resolved please do leave a comment.
You may like the following Python tutorials:
- How to create a string in Python
- How to create a variable in python
- Python get an IP Address
- Python – stderr, stdin and stdout
- Increment and Decrement operators in Python
- Python Anonymous Function
- Python Read CSV File and Write CSV File
- Hash table in python
- Block Indentation in Python
In this Python tutorial, learned about send email using Python.
- Sending an email using Python over localhost
- 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 without password
- send email using python mini-project
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.