How to send a simple email using Python


In this tutorial we will see how to send a simple email using Python 3. Simple email means we will send a text message using Gmail SMTP server. You may find useful other tutorials on sending emails with different formats. We will connect to both TLS and SSL ports over Gmail SMTP server.

We will use here email package from Python programming language.


Python 3.8.0, Gmail Security Settings, Gmail SMTP Server –, Gmail SMTP Port – 587

Creating Python Script

We will create below Python script called You can choose any location to place this file. Make sure your Python is accessible from anywhere using command prompt.

import smtplib

from email.message import EmailMessage

msg = EmailMessage()
msg.set_content('Email sending example using Python. It\'s Simple Text Message')

fromEmail = ''
toEmail = ''

msg['Subject'] = 'Simple Text Message'
msg['From'] = fromEmail
msg['To'] = toEmail

s = smtplib.SMTP('', 587)


s.login(fromEmail, 'gmail address's password')

In the above Python script, we first import smtplib for sending the email.

In the next line we import email module for creating email message.

Next we create the EmailMessage() object and set the body of the message using set_content() function.

Related Posts:

Then we set the subject for the email and we also set from and to email addresses to send and receive the email respectively.

Next we create a session using Gmail SMTP server – and port – 587.

We need to issue STARTTLS command otherwise you will get the following error:

#smtplib.SMTPSenderRefused: (530, b'5.7.0 Must issue a STARTTLS command first. p7sm24605501pfn.14 - gsmtp', '')

You will get below error if your security level is high:

#smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 x10sm26098036pfn.36 - gsmtp')

Therefore you need to lower your Gmail’s security settings.

Using SSL Port 465

If you want to use SSL port 465 to establish the secure connection with Gmail SMTP server then do the following changes:

Replace s = smtplib.SMTP_SSL('', 587) by s = smtplib.SMTP_SSL('', 465).

Remove line s.starttls().

Testing the Email Sending

Just executing the file using command line tool will send the email.

Once your email successfully sent you will see the following output in Gmail Inbox:

how to send a simple email using python

As I have sent from my gmail address to my gmail address, so the from email address you see as me in the above image.

When you open the message you will see below output as shown in the image:

how to send a text email using python

That’s all. Hope you got an idea how to send simple text message through email using Python 3.

You can also use your own SMTP server and port to send email using Python.

Source Code


Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *