DEV Community

Cover image for Simple Script To Send Emails In Python
All About Python
All About Python

Posted on

Simple Script To Send Emails In Python

Simple Script To Send Emails In Python -<br>
Emails

Emails are, nowadays, a common way of formal communication, which is also good for the transfer of files easily from person to person. Almost every person who has some identity over the internet, or simply uses it, has an email ID of his own, be it Gmail or outlook.

Now of all the awesome stuff that can be done in python, one of those is to be able to send or receive emails. Python programming
libraries can be used to send mails or to list all the mails within your email account. You can also perform some basic actions, like marking the mail as read, using python.

And in this blog, I am gonna show you, how you can do this yourself.

About Mail Servers

Simple Script To Send Emails In Python - SMTP and IMAP Mail<br>
Servers

Before we start with the coding part, you need to have some basic
information about mails and mail servers.

Mail servers are basically servers that are used to manage emails, Outlook, Gmail, Yahoo, Hotmail, etc. have their own mail servers that manage their mail services. Mail servers can further be classified into two categories;

SMTP Server

SMTP stands for Simple Mail Transfer Protocol.This server is responsible for sending or transferring mail from server to server i.e. whenever you send a mail to someone, you typically make use of the SMTP server.

IMAP Server

IMAP stands for Internet Message Access Protocol.This server is responsible for storing and listing mails from your server i.e. whenever you open your Gmail or Outlook, you typically make use of the IMAP server.

SSL and TLS

There are two types of encryption protocols used for
emails, SSL (Secure Socket Layer) and TLS (Transport Layer Security).
Whenever you will connect to any mail server, you will connect through one of these protocols. Each protocol has its port assigned to the server.

TLS - port 587
SSL - port 465

Although Gmail and Outlook server support both these protocols, we are gonna use only TLS protocol in this post for simplicity.

Sending Mails using Python

Simple Script To Send Emails In Python - sending mails using<br>
python

Now that we are clear about mail servers, let's create our first script to send mail using python

Installing the library

Simple Script To Send Emails In Python - python library to send<br>
mails

We will be using the smtplib library of python to send Gmail or Outlook mail. This library comes built-in in python, so you don't need to download it from elsewhere.

Creating the script

Here's how the script would look like

Simple Script To Send Emails In Python - python script to send<br>
mails

The script may look complicated, but we will go line-by-line to discuss each function and class of the script and understand its use

Simple python script to send emails - import<br>
libraries

The script starts with importing smtplib and getpass library. We are using the getpass library so that we can retrieve the password from the
user.

simple script to send emails in python - email and<br>
password

After that, we ask the user to enter the credentials for their mail account, which will be used to send the mail. We use getpass to ask the user for the password. Since we are using getpass, the password that the user will enter will not be displayed on the screen but will be saved within the variable.

simple script to send emails in python - set host and<br>
port

In the next step, we set up the SMTP server host and port to be used. If the entered email ID is a Gmail account, the host will be set to Gmail SMTP server, or else if it is Outlook, the ost
will be set to Outlook SMTP server.
We set the port to 587 as we had discussed above within the 'SSL and TLS heading. In case if the entered email ID cannot be identified as Gmail or
Outlook, the script will give an error message and exit.

simple script to send emails in python - smtplib.SMTP class<br>
object

In the next step, we will create the SMTP class object, which will be used to perform the actions. We create an object of smtplib.SMTP class and save the object by the name 'server'. The class object requires two parameters, the hostname, and the port. 

Once we have created the object, we call the ehlo() function of the class object, which is basically used to send a greeting message to the mail server. This step is crucial, as not performing this step may cause problems in communicating with the mail server. 

simple script to send emails in python - start tls<br>
encryption

After receiving a successful response from the server, we call the starttls() function to start TLS encryption. This step is only required for TLS connection and not for SSL connection.

simple script to send emails in python - login to mail<br>
server

After this, we call the login() function to log in to the mail account. The function requires two parameters, the email ID and the password, which we had retrieved from the user.

simple script to send emails in python - get email content from user

Once we have successfully logged in, we ask the user for the receiver's email ID, mail's subject, and mail body.

simple script to send emails in python - sendmail<br>
function

And finally, we call the sendmail() function and pass three parameters, sender mail ID, receiver mail ID, and the mail body (created by merging mail subject and mail content).

Here is the full code 

import smtplib
import getpass

# Get email ID and password from user
email = input("Enter email ID: ")
password = getpass.getpass("Enter password: ")

# Set SMTP host and port
if "gmail" in email:
    host = "smtp.gmail.com"
    port = 587
elif "outlook" in email:
    host = "smtp-mail.outlook.com"
    port = 587
else:
    print("Invalid email ID, please try again")
    exit(0)

# Create SMTPLib object and contact server
server = smtplib.SMTP(host, port)
check = server.ehlo()
if check[0] == 250:
    print("Successfully contacted mail server")
else:
    print("Unable to contact server")
    exit(0)

# Start TLS encryption (only to be done if conencting to port 587 i.e. TLS)
server.starttls()

# Logging into the server
try:
    server.login(email, password)
    print("Login successful")
except smtplib.SMTPAuthenticationError as ex:     
    print("Exception:", ex)    
    exit(0)

# Get email details from user
sender_mail = email
receiver_email = input("Enter receiver's email: ")
subject = input("Enter email subject: ")
content = input("Enter email content: ")

# Create email body by merging emails object and content
body = "Subject: " + subject + '\n' + content

# Send the mail
output = server.sendmail(sender_mail, receiver_email, body)
if not len(output):
    print("Send mail successfully")
else:
    print("Unable to send mail, please try again")    
    exit(0)
Enter fullscreen mode Exit fullscreen mode

And that's it, you have successfully sent a mail through python

Conclusion

In this blog, I have only covered sending mail through python. I will soon create another blog that will deal with accessing email from accounts by contacting the IMAP servers using python.

Hope you liked this blog

Stay safe, stay blessed, and thanks for reading.

Latest comments (0)