Python SMTP Module














































Python SMTP Module



Python SMTP Module


What Is SMTP?

Simple Mail Transfer Protocol is an application layer protocol in the OSI model. It lets a user send mail to another. Since this is a push protocol, we can use it to send an mail. At the receiver, this mail is retrieved using protocols POP (Post Office Protocol) and IMAP (Internet Message Access Protocol).

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

We need to start a server that is always listening for a request. As a client, we open a TCP connection to this server and then send the mail. When the server listens for a TCP connection from a client, it initiates a connection on port 587.



          



SMTP Protocol

The SMTP model is of two types :

  1. End-to-end method.

  2. Store-and- forward method.


The Simple Mail Transfer Protocol (SMTP) handles sending and routing email between mail servers.

Python provides smtplib module, which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.


Here is an example of how to create an SMTP object.


        



Create and Send a Simple Email


Installing smtplib

Open up your computer's command prompt.

On Windows PC, this is done by going to Start, then typing in "CMD", clicking the "CMD" app to open it up.

In the command prompt, type in:

C:\Users> pip install smtplib

 

Then hit Enter.

Setting up everything

We are going to send emails using a Gmail account. However, Google will not allow logging in via smtplib because it has flagged this type of login as "less secure". To solve this, go to https://www.google.com/settings/security/lesssecureapps while you're logged in to your Google account, and "Allow less secure apps".


            


We will follow the following steps to accomplish this process:

  • Create an SMTP object for connection to the server.

  • Log in to your account.

  • Define your message headers and login credentials.

  • Create a MIMEMultipart message object and attach the relevant headers to it, i.e. From, To, and Subject.

  • Attach the message to the message MIMEMultipart object.

  • Finally, send the message.



Let%u2019s start by creating a simple script that sends one text email to other people from your account.

Create a python file, for example, smtplib_example.py, and write:

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

import smtplib

import os


# Retrieving Email and Password From Enviorment Variables

USER_EMAIL = os.environ.get('EMAIL_ADDRESS')  # Your Email Address

USER_PASSWORD = os.environ.get('EMAIL_PASS')  # Your Email Password


# Creating Message Instance

msg = MIMEMultipart()


Message = 'This is a Test Message'


# Additional Parameters of the Message

msg['from'] = USER_EMAIL

msg['to'] = RECIEVER%u2019s EMAIL # Target's Email

msg['subject'] = 'Test Subject'


msg.attach(MIMEText(Message,'plain'))


print('Sending the Mail..')

try:

# Creating SMTP Instance 

server = smtplib.SMTP(host='smtp.gmail.com',port=587)


# Create Secure Transport Layer Connection

server.starttls()


# Login to your Account

server.login(USER_EMAIL,USER_PASSWORD)


# Sending Messsage to the Client

server.sendmail(USER_EMAIL, msg['to'], msg.as_string())


print(%u2018Message Sent Successfully..... ' )


except Exception as e :

print(f'Exception Occured ! \n {e}')


finally:

# Close Connection

server.quit()



Execute your code, and if no error occurs, then the email was successful. Now go to your inbox and you should able to see your Message In your Inbox.

Create and Send an Email With an Attachment

In this example, we are going to send an email with an image attachment. The process is similar to sending a plain text email.

  • Create an SMTP object for connection to the server.

  • Log in to your account.

  • Define your message headers and login credentials.

  • Create a MIMEMultipart message object and attach the relevant headers to it, i.e. From, To, and Subject.

  • Create a MIMEImage Image object then Read and attach the image to the message MIMEMultipart object.

  • Finally, send the message.

Let%u2019s start by creating a simple script that sends one Image Attached mail to other people from your account.


from email.mime.multipart import MIMEMultipart

from email.mime.image import MIMEImage

from email.mime.text import MIMEText

import smtplib

import os


# Retreiving Email and Password From Enviorment Variables

USER_EMAIL = os.environ.get('EMAIL_ADDRESS')  # Your Email Address

USER_PASSWORD = os.environ.get('EMAIL_PASS')  # Your Email Password


# Creating Message Instance

msg = MIMEMultipart()


Message = 'This is a Test Message'


# Additional Parameters of the Message

msg['from'] = USER_EMAIL

msg['to'] = RECIEVER%u2019s EMAIL # Target's Email

msg['subject'] = 'Demo Image Attachment'


msg.attach(MIMEText(Message,'plain'))


with open('image.png', 'rb') as file:     # Replace Your Filename with Image.png

    content = file.read()

    img = MIMEImage(content)

    msg.attach(img)

    file.close()


print('Sending the Mail..')

try:

# Creating SMTP Instance 

server = smtplib.SMTP(host='smtp.gmail.com',port=587)


# Create Secure Transport Layer Connection

server.starttls()


# Login to your Account

server.login(USER_EMAIL,USER_PASSWORD)


# Sending Messsage to the Client

server.sendmail(USER_EMAIL,msg['to'],msg.as_string())


print(%u2018Message Sent Successfully..... ' )


except Exception as e :

print(f'Exception Occured ! \n {e}')


finally:

# Close Connection

server.quit()



Run This python file, smtplib_example.py and if no error occurs, then the email was successful.

Now go to your Email and you should be able to see the Attached Image Sent through the python file. 


Comments