Free Web Development Online Tutorials, Learn to Code
How to send email using Python code, Python Email Sending Example

Python sending email using smtp

In this tutorial you will learn how to write an python email sending program, sending email using smtp with attachment.

Send email from Python Code

The first step is to create an SMTP object and set up all details, each object will be used for connection with one server.

We need to import SMTP library using import smtplib

Here in example i have hardcoded all details of SMTP, ideally you should read all SMTP details from ini configuration file.

Here are some important libraries you need to refer for sending email in python

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

Now, let's write very simple code to send one email to some particular email id, later we see how to make it more dynamic. Following code demonstrate sending email.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class EmailExample(object):
def __init__(self):
self.Title = "Email Sending Example";
self.Port=80;
self.Host_Address="smtp.gmail.com";
self.SmtpUsername="webtrainingroom@gmail.com";
self.SmtpPassword="XXXXX";
    def SendEmail(self):
        # set up the SMTP server
        s = smtplib.SMTP(host=Host_Address, port=Port)
        s.starttls()
        s.login(SmtpUsername, SmtpPassword)
        
        msg = MIMEMultipart();
        msg['From']=SmtpUsername;
        msg['To']=email;
        msg['Subject']="Hello! I invite You";
        message ="Invitation letter ....body content";
        msg.attach(MIMEText(message, 'plain'))
        
        s.send_message(msg);
        
        del msg;
        s.quit();

Now let’s understand the above code step by step.

Step 1

In code below I am setting up SMTP details when my EmailExample class is initialised.

Note: Here I have hardcoded all values, but ideally you need to fetch all those values from configuration file

def __init__(self):
    self.Title = "Email Sending Example";
    self.Port=80;
    self.Host_Address="smtp.gmail.com";
    self.SmtpUsername="webtrainingroom@gmail.com";
    self.SmtpPassword="XXXXX";
Step 2

Create a new instance of SMTP server with host and port number, then login to SMTP using your SMTP credentials.

s = smtplib.SMTP(host=Host_Address, port=Port)
s.starttls()
s.login(SmtpUsername, SmtpPassword)
Step 3

Creating a new MIMEMultipart object, and then setting up all message details (again, I have hardcoded all values just for demo purpose).

msg = MIMEMultipart();
msg['From']=SmtpUsername;
msg['To']=email;
msg['Subject']="Hello! I invite You";
message ="Invitation letter ....body content";
msg.attach(MIMEText(message, 'plain'))
        
s.send_message(msg);

Finally, delete the message and quit SMTP, even if don’t write following code, still email sending will be done, but as a good practice we should always free up the resources explicitly.

del msg;
s.quit();

Now here is some additional functionality you can use if you are writing an email sending application in python.

Validate Email in Python

Validate an email address using python, check if each email format is correct before sending email, this will help maintaining SMTP reputation

import re

def IsValidEmail(self, email):
    regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$';
    if(re.search(regex,email)):  
        print("Valid Email")            
    else:  
        print("Invalid Email")  

Send Email from your Gmail account in Python

You can send email using your Gmail account from Python code.

import smtplib

server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(True)

# start TLS for security
server.starttls()

# Authentication 
server.login("sender_email_id", "sender_email_id_password")

Check if email exists on server

We should verify each email address before sending email, The SMTP protocol includes a command to check on server whether an address is valid.

verify method internally uses VRFY command. (Usually VRFY is disabled to prevent spammers from finding legitimate email addresses), but we should always check in our code

import smtplib

server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(True)  

# show communication with the server
try:
    dhellmann_result = server.verify('abc@fmail.com')
    notthere_result = server.verify('notthere')
finally:
    server.quit()

print 'dhellmann:', dhellmann_result
print 'notthere :', notthere_result
 
Send email using Python code

Python programming examples | Join Python Course