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.
from email.message import EmailMessageEMAIL_ADDRESS = 'firstname.lastname@example.org'
EMAIL_PASSWORD = 'akshita09@'contacts = [ EMAIL_ADDRESS, 'email@example.com']msg = EmailMessage()
msg['Subject'] = 'Hey!'
msg['From'] = EMAIL_ADDRESS
msg['To'] = 'firstname.lastname@example.org'msg.set_content('This is a plain text email')msg.add_alternative("""\<!DOCTYPE html>
<h3 style="color:Black;"> How are you ?</h3>
""", subtype='html')with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
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.