Sending mail in python

Sending mail in python

Introduction

Sending mail is a great feature that python provides. We can send mail in real-time by using Simple Mail Transfer Protocol (SMTP).

SMTP is often referred as smptlib that is a python library helps in sending mail. This module defines SMTP client session object. This object can then be used to send an email on any internet session. One most important thing to do is that you must turn on less secure app access on your gmail account. You won’t get email at a time it will take time for delivery.

Python is awesome as it has built in everything. We must import the smptlib library. Then we must declare our mail and password. We must set SMTP connection. After that we must login using our email and password in python code. Then give the receiver email and message. Then execute the program the mail is sent.


Sending mail source code

import smtplib
import random

MY_EMAIL = "example@gmail.com"
MY_PASSWORD = "password"

with smtplib.SMTP("smtp.gmail.com") as connection:
    connection.starttls()
    connection.login(user=MY_EMAIL, password=MY_PASSWORD)
    connection.sendmail(from_addr=MY_EMAIL,
                            to_addrs=MY_EMAIL,
                            msg=f"Subject:Monday Motivation"
                            )