How to Send Email Using Python

Email automation is a powerful feature in modern applications, enabling notifications, reports, user communication, and more. Python, with its robust standard library and third-party packages, makes it easy to send emails programmatically.

This post provides code snippets to send email through python, the python email package is used in the code example to send an email with python.

Prerequisites
  • Python 3 installed
  • Access to an SMTP server (e.g., Gmail, Outlook, Mailtrap)
  • Basic knowledge of Python programming

Note:- If you're using Gmail, you may need to enable “Less secure app access” or use App Passwords if two-factor authentication is enabled.

How to Send Email Using Python

email python
Python Send Email

Getting Started

The python email module(smtplib module) defines an SMTP client (called python SMTP client) session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.

This module is a native module (inbuild with python), it does not require to install an external library to send email through python.

Python Send Email

To send an email using Python, the built-in smtplib and email libraries are commonly used. Here's a simple example that sends an email via a SMTP server:

Send Mail With Plain Text

Here's a simple Python code to send a plain text email using the built-in smtplib and email libraries:

Python Code
 # Sending a emails without attachments using Python.  
 # importing the required library(python email module).   
 import smtplib   
   
 # email sender python  
 sender = 'sender_email_id'  
   
 # Sender password  
 password="sender_password"  
   
 #email receiver python  
 receivers = ['receiver_email_id']  
 
 # message to be sent   
 message = "Content to be sent" 
   
 # creates python smtp server object  
 email = smtplib.SMTP('python smtp email:smtp_host_name', Port_Number)   
    
 # smtp login python  
 email.login(sender, password)   
        
 # python send email smtp   
 email.sendmail(sender, receivers, message)   
    
 # terminating the session   
 email.quit()        

Send Mail with HTML
Python Code
 import smtplib  
 from email.message import EmailMessage  
 # Email details  
 sender = 'your_email@example.com'  
 recipient = 'recipient@example.com'  
 subject = 'Test Email from Python'  
 body = 'Hello, this is a test email sent from Python!'  
 # Compose the email  
 msg = EmailMessage()  
 msg['From'] = sender  
 msg['To'] = recipient  
 msg['Subject'] = subject  
 msg.set_content(body)  
 msg.add_alternative("""  
 <html>  
  <body>  
   <h1 style="color:blue;">Welcome!</h1>  
   <p>This is an <b>HTML email</b> sent from <i>Python</i>.</p>  
  </body>  
 </html>  
 """, subtype='html')  
 # Send the email using SMTP  
 with smtplib.SMTP('smtp.gmail.com', 587) as server:  
   server.starttls()  
   server.login(sender, 'your_email_password')  
   server.send_message(msg)  
 print("Email sent successfully!")  

Send Mail with Attachment

To send email via python with attachment, along with the smtplib library the following libraries need to be imported.

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

The following code constain the python script to send email with attachment. The code contains the steps how to read the attachment from local computer and attachech it with mail body.

Python Code
 # python send email with attachment  
   
 # importing the required library(python email module).  
 import smtplib   
 from email.mime.multipart import MIMEMultipart   
 from email.mime.text import MIMEText   
 from email.mime.base import MIMEBase   
 from email import encoders   
   
 # email sender python  
 sender = 'sender_email_id'  
   
 # Sender password  
 password="sender_password"  
   
 #email receiver python  
 receivers = ['receiver_email_id']  
   
 # MIMEMultipart   
 _Mail = MIMEMultipart()   
   
 # senders email address   
 _Mail['From'] = sender   
   
 # receivers email address   
 _Mail['To'] = receivers   
   
 # the subject of mail  
 _Mail['Subject'] = "subject_of_the_mail"  
 
  filename = "Path of file (file_name_with_extension)"  
   
 # the body of the mail   
 body = "body_of_the_mail"  
   
 #The body and the attachments for the mail  
 _Mail.attach(MIMEText(body, 'plain'))   
   

 # Open the file as binary mode with readonly  
 # rb is a flag for readonly   
 attachment = open(filename, "rb")   
   
 # MIMEBase  
 payload = MIMEBase('application', 'octet-stream')   
   
 # To change the payload into encoded form   
 payload .set_payload((attachment).read())   
   
 # encode into base64   
 encoders.encode_base64(payload )   
   
 #add payload header with filename  
 payload .add_header('Content-Disposition', "attachment; filename= %s" % filename)   
   
 # attach the instance 'p' to instance '_Mail'   
 _Mail.attach(payload )   
   
 #python smtp client  
 # creates python smtp client object  
 email = smtplib.SMTP('email_host_name', email_port_number)   
   
 #enable security  
 email.starttls()   
   
 # smtp login python  
 email.login(fromaddr, password)   
   
 # Converts the Multipart _Mail into a string   
 message = _Mail.as_string()   
   
 # python send email smtp   
 email.sendmail(sender, receivers, message)   
   
 # terminating the session   
 email.quit()      

In the above code, the MIME objects are created in order to store the sender and receiver information and some other details(subject, body of mail). MIME is also needed to set the attachment with the mail.

Send Mail from Python Example

The following example contains python code to send mail from python using gmail SMTP server with attachment.

Python Code
 # python send email with attachment  
   
 # importing the required library(python email module).  
 import smtplib   
 from email.mime.multipart import MIMEMultipart   
 from email.mime.text import MIMEText   
 from email.mime.base import MIMEBase   
 from email import encoders   
   
 # email sender python  
 sender = 'kailashsblogs@gmail.com'  
   
 # Sender password  
 password="###########"  
   
 #email receiver python  
 receivers = ['kailashsblogs@hotmail.com']  
   
 # MIMEMultipart   
 _Mail = MIMEMultipart()   
   
 # senders email address   
 _Mail['From'] = sender   
   
 # receivers email address   
 _Mail['To'] = receivers   
   
 # the subject of mail  
 _Mail['Subject'] = "python send email test"  
   
 # the body of the mail   
 body = "Test Python Gmail Send Email"  
   
 #The body and the attachments for the mail  
 _Mail.attach(MIMEText(body, 'plain'))   
   
 filename = "D:\document\testfile.txt"  
 # Open the file as binary mode with readonly  
 # rb is a flag for readonly   
 attachment = open(filename, "rb")   
   
 # MIMEBase  
 payload = MIMEBase('application', 'octet-stream')   
   
 # To change the payload into encoded form   
 payload .set_payload((attachment).read())   
   
 # encode into base64   
 encoders.encode_base64(payload )   
   
 #add payload header with filename  
 payload .add_header('Content-Disposition', "attachment; filename= %s" % filename)   
   
 # attach the instance 'p' to instance '_Mail'   
 _Mail.attach(payload )   
   
 #python smtp gmail  
 email = smtplib.SMTP('smtp.gmail.com', 587)   
   
 #enable security  
 email.starttls()   
   
 # smtp login python  
 email.login(fromaddr, password)   
   
 # Converts the Multipart _Mail into a string   
 message = _Mail.as_string()   
   
 # python send email gmail  
 email.sendmail(sender, receivers, message)   
   
 # terminating the session   
 email.quit()   
   

Summary

Python makes email automation easy with just a few lines of code. Whether you're sending simple alerts or styled reports with attachments, the smtplib and email libraries cover most use cases.

Thanks

Kailash Chandra Behera

An IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies. Demonstrated expertise in delivering all phases of project development—from initiation to closure—while aligning with business objectives to drive process improvements, competitive advantage, and measurable bottom-line gains. Proven ability to work independently and manage multiple projects successfully. Committed to the efficient and effective development of projects in fast-paced, deadline-driven environments. Skills: Proficient in designing and developing applications using various Microsoft technologies. Total IT Experience: 13+ years

Previous Post Next Post

نموذج الاتصال