Simple Script To Send Emails In Python
Tags: python, programming, tutorial, beginners
Published: 2021-10-28 06:02:57

[![Simple Script To Send Emails In Python -
Emails](https://1.bp.blogspot.com/-NlhES-ojmpE/YR1NQnS04KI/AAAAAAAAAeA/S22tLiOAdaMIEjtTZhQ-Pxw15cTZ9_JKQCLcBGAsYHQ/w640-h358/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2BEmails.png "Simple Script To Send Emails In Python - Emails")](https://1.bp.blogspot.com/-NlhES-ojmpE/YR1NQnS04KI/AAAAAAAAAeA/S22tLiOAdaMIEjtTZhQ-Pxw15cTZ9_JKQCLcBGAsYHQ/s1280/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2BEmails.png)

[Emails](https://en.wikipedia.org/wiki/Email) 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](https://en.wikipedia.org/wiki/Gmail) or [outlook](https://en.wikipedia.org/wiki/Microsoft_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](https://en.wikipedia.org/wiki/Email). 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
Servers](https://1.bp.blogspot.com/-alQJy_Z_noE/YR1NmQV9u_I/AAAAAAAAAeI/fQ1lEWQGBB0tapeGv5XBTTOx8-1PeBuDgCLcBGAsYHQ/w640-h224/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2BSMTP%2Band%2BIMAP%2BMail%2BServers.jpg "Simple Script To Send Emails In Python - SMTP and IMAP Mail Servers")](https://1.bp.blogspot.com/-alQJy_Z_noE/YR1NmQV9u_I/AAAAAAAAAeI/fQ1lEWQGBB0tapeGv5XBTTOx8-1PeBuDgCLcBGAsYHQ/s2997/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2BSMTP%2Band%2BIMAP%2BMail%2BServers.jpg)

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](https://en.wikipedia.org/wiki/Email), [Outlook](https://en.wikipedia.org/wiki/Microsoft_Outlook), [Gmail](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol).This server is responsible for storing and listing mails from your server i.e. whenever you open your [Gmail](https://en.wikipedia.org/wiki/Gmail) or [Outlook](https://en.wikipedia.org/wiki/Microsoft_Outlook), you typically make use of the IMAP server.

**SSL and TLS**

There are two types of encryption protocols used for
[emails](https://en.wikipedia.org/wiki/Email), SSL ([Secure Socket Layer](https://en.wikipedia.org/wiki/Transport_Layer_Security#SSL_1.0,_2.0,_and_3.0)) and TLS ([Transport Layer Security](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/Gmail) and [Outlook](https://en.wikipedia.org/wiki/Microsoft_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
python](https://1.bp.blogspot.com/-lkyurw5VAtI/YR1OAnZAUaI/AAAAAAAAAeQ/xbT0ZOWMRNIDmzKLnDOs_dvsuakk7G_KACLcBGAsYHQ/w640-h432/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2BSending%2Bmails%2Busing%2Bpython.png "Simple Script To Send Emails In Python - sending mails using python")](https://1.bp.blogspot.com/-lkyurw5VAtI/YR1OAnZAUaI/AAAAAAAAAeQ/xbT0ZOWMRNIDmzKLnDOs_dvsuakk7G_KACLcBGAsYHQ/s1280/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2BSending%2Bmails%2Busing%2Bpython.png)

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
mails](https://1.bp.blogspot.com/-eeDjAGu_aLA/YR1OWkDQwxI/AAAAAAAAAeY/wo06MeFGVRgWl3OiRFFy3239_XEkmz7OgCLcBGAsYHQ/w640-h426/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bpython%2Blibrary%2Bto%2Bsend%2Bmails.jpg "Simple Script To Send Emails In Python - python library to send mails")](https://1.bp.blogspot.com/-eeDjAGu_aLA/YR1OWkDQwxI/AAAAAAAAAeY/wo06MeFGVRgWl3OiRFFy3239_XEkmz7OgCLcBGAsYHQ/s2048/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bpython%2Blibrary%2Bto%2Bsend%2Bmails.jpg)

We will be using the smtplib library of python to send [Gmail](https://en.wikipedia.org/wiki/Gmail) or [Outlook](https://en.wikipedia.org/wiki/Microsoft_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
mails](https://1.bp.blogspot.com/-uHUX2Nso6uQ/YR1OxolUNqI/AAAAAAAAAeg/DRGyTX_tZjEaH6XIUj5f0AXftEiu3lMzwCLcBGAsYHQ/w640-h342/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bpython%2Bscript%2Bto%2Bsend%2Bmails.PNG "Simple Script To Send Emails In Python - python script to send mails")](https://1.bp.blogspot.com/-uHUX2Nso6uQ/YR1OxolUNqI/AAAAAAAAAeg/DRGyTX_tZjEaH6XIUj5f0AXftEiu3lMzwCLcBGAsYHQ/s1366/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bpython%2Bscript%2Bto%2Bsend%2Bmails.PNG)

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
libraries](https://1.bp.blogspot.com/-z-rc47TPTEQ/YR1PQRCKI7I/AAAAAAAAAeo/oVF72gI7pvwPB4ERR23uN8TSpmqs0fV3wCLcBGAsYHQ/w400-h124/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bimport%2Blibraries.png "Simple python script to send emails - import libraries")](https://1.bp.blogspot.com/-z-rc47TPTEQ/YR1PQRCKI7I/AAAAAAAAAeo/oVF72gI7pvwPB4ERR23uN8TSpmqs0fV3wCLcBGAsYHQ/s152/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bimport%2Blibraries.png)

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
password](https://1.bp.blogspot.com/-wDGAtsEE83s/YR1Q8BOJQnI/AAAAAAAAAew/KQnYH71cEcEZy7RAVeQtFhQ8NzL6XHocACLcBGAsYHQ/w400-h84/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bemail%2Band%2Bpassword.PNG "simple script to send emails in python - email and password")](https://1.bp.blogspot.com/-wDGAtsEE83s/YR1Q8BOJQnI/AAAAAAAAAew/KQnYH71cEcEZy7RAVeQtFhQ8NzL6XHocACLcBGAsYHQ/s403/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bemail%2Band%2Bpassword.PNG)

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
port](https://1.bp.blogspot.com/--nIYKydzfNo/YR1RNf-1UKI/AAAAAAAAAe4/LAX8PHAS4Gkmd9wrcu40gA2g0i-dlq8DgCLcBGAsYHQ/w400-h194/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bset%2Bhost%2Band%2Bport.PNG "simple script to send emails in python - set host and port")](https://1.bp.blogspot.com/--nIYKydzfNo/YR1RNf-1UKI/AAAAAAAAAe4/LAX8PHAS4Gkmd9wrcu40gA2g0i-dlq8DgCLcBGAsYHQ/s434/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bset%2Bhost%2Band%2Bport.PNG)

In the next step, we set up the SMTP server host and port to be used. If the entered email ID is a [Gmail](https://en.wikipedia.org/wiki/Gmail) account, the host will be set to [Gmail](https://en.wikipedia.org/wiki/Gmail) SMTP server, or else if it is [Outlook](https://en.wikipedia.org/wiki/Microsoft_Outlook), the ost
will be set to [Outlook](https://en.wikipedia.org/wiki/Microsoft_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](https://en.wikipedia.org/wiki/Gmail) or
[Outlook](https://en.wikipedia.org/wiki/Microsoft_Outlook), the script will give an error message and exit.

[![simple script to send emails in python - smtplib.SMTP class
object](https://1.bp.blogspot.com/-cUFEIlwJ1yM/YR1RXHQteoI/AAAAAAAAAe8/S_Q-rUbNlAE4Llw-Pd9gMuPfMJJ4GPnWQCLcBGAsYHQ/w400-h139/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bsmtplib.SMTP%2Bclass%2Bobject.PNG "simple script to send emails in python - smtplib.SMTP class object")](https://1.bp.blogspot.com/-cUFEIlwJ1yM/YR1RXHQteoI/AAAAAAAAAe8/S_Q-rUbNlAE4Llw-Pd9gMuPfMJJ4GPnWQCLcBGAsYHQ/s461/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bsmtplib.SMTP%2Bclass%2Bobject.PNG)

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
encryption](https://1.bp.blogspot.com/-QAltlFCcouA/YR1Rf9sAzmI/AAAAAAAAAfE/Yvr9_HpdvDsV6sc37BErPvIo9P6SgJk5QCLcBGAsYHQ/w400-h41/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bstart%2Btls%2Bencryption.png "simple script to send emails in python - start tls encryption")](https://1.bp.blogspot.com/-QAltlFCcouA/YR1Rf9sAzmI/AAAAAAAAAfE/Yvr9_HpdvDsV6sc37BErPvIo9P6SgJk5QCLcBGAsYHQ/s537/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bstart%2Btls%2Bencryption.png)

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
server](https://1.bp.blogspot.com/-o88SInWtQ6Q/YR1R4HZC88I/AAAAAAAAAfU/nEAcbcKHrzoRjv4qOHB-FNbkqiPMRB8aQCLcBGAsYHQ/w400-h153/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Blogin%2Bto%2Bmail%2Bserver.PNG "simple script to send emails in python - login to mail server")](https://1.bp.blogspot.com/-o88SInWtQ6Q/YR1R4HZC88I/AAAAAAAAAfU/nEAcbcKHrzoRjv4qOHB-FNbkqiPMRB8aQCLcBGAsYHQ/s426/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Blogin%2Bto%2Bmail%2Bserver.PNG)

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](https://1.bp.blogspot.com/-E0rbx8h68ME/YR1R_gXFJTI/AAAAAAAAAfc/ASO4-kqbgCs0EaiAzU0HQGZS9iUK_umsACLcBGAsYHQ/w400-h106/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bget%2Bemail%2Bcontent.PNG "simple script to send emails in python - get email content from user")](https://1.bp.blogspot.com/-E0rbx8h68ME/YR1R_gXFJTI/AAAAAAAAAfc/ASO4-kqbgCs0EaiAzU0HQGZS9iUK_umsACLcBGAsYHQ/s458/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bget%2Bemail%2Bcontent.PNG)

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
function](https://1.bp.blogspot.com/-eytSNF_SFSs/YR1SHvioJfI/AAAAAAAAAfg/I1r1aQfn-SMukMEHE9V36aZY_yrOU8eEwCLcBGAsYHQ/w400-h125/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bsend%2Bmail.PNG "simple script to send emails in python - sendmail function")](https://1.bp.blogspot.com/-eytSNF_SFSs/YR1SHvioJfI/AAAAAAAAAfg/I1r1aQfn-SMukMEHE9V36aZY_yrOU8eEwCLcBGAsYHQ/s495/Simple%2BScript%2BTo%2BSend%2BEmails%2BIn%2BPython%2B-%2Bsend%2Bmail.PNG)

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)
                
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.