Send Emails Using Python

Akshita Chugh
2 min readMar 10, 2022

--

In this article, we would learn to send emails using Python. Sending emails manually is a time-consuming and error-prone task, but it’s easy to automate this task using python.

Step 1: Set up a new Gmail account

If you decide to use a Gmail account for sending the emails then it is recommended to set up a new account for the development of this code. This is because you’ll have to adjust your email account’s security settings to allow access from your Python code, and that might accidentally expose your login details.

Turn Allow less secure apps to ON. for your new google account.

Step 2: Setting up a Local SMTP Server

Simple Mail Transfer Protocol (SMTP) is a protocol which handles sending an e-mail between mail servers. Python has a built-in smtplib module that is used for sending emails. This module help defines an SMTP client session object that can be used to send mails to any Internet machine with an SMTP or ESMTP listener daemon.

import os
import smtplib
import imghdr
from email.message import EmailMessage
EMAIL_ADDRESS = 'akshita.chugh09@gmail.com'
EMAIL_PASSWORD = 'akshita09@'
contacts = [ EMAIL_ADDRESS, 'akshita.chugh09@gmail.com']msg = EmailMessage()
msg['Subject'] = 'Hey!'
msg['From'] = EMAIL_ADDRESS
msg['To'] = 'akshita.chugh024@gmail.com'
msg.set_content('This is a plain text email')msg.add_alternative("""\<!DOCTYPE html>
<html>
<body>
<h3 style="color:Black;">Hi</h3>
<h3 style="color:Black;"> How are you ?</h3>

</body>
</html>
""", subtype='html')
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
smtp.send_message(msg)

Conclusion

Sending emails via SMTP in python makes sending email a piece of cake as it is easy to set up, highly cost effective and is platform agnostic. However, it is less secure, does not have the facility of built- in analytics ,and it takes longer to send emails.

--

--

Akshita Chugh
Akshita Chugh

Written by Akshita Chugh

I am a Data Analyst at EXL and I have done masters in economics from Jawaharlal Nehru University

No responses yet