python smtp mail code example

Example 1: send html smtp email python

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

def send_email():
    sender = FROM_EMAIL
    receiver = ["[email protected]","[email protected]"] # emails in list for multiple or just a string for single.
    msg = MIMEMultipart()
    msg['From'] = FROM_NAME # The name the email is from e.g. Adam
    msg['To'] = TO_NAME # The receivers name
    msg['Subject'] = SUBJECT
    with open(HTML_TEMPLATE) as f:
        html = f.read()
    part = MIMEText(html, 'html')
    msg.attach(part)

    with smtplib.SMTP("smtp.gmail.com") as connection:
        connection.starttls()
        connection.login(CONNECTION USERNAME/EMAIL, CONNECTION PASSWORD)
        connection.sendmail(sender, receiver, msg.as_string())

Example 2: smtp in python

#>>>>>>>>>>>>>>>>>>> GIVE AN UP VOTE IF YOU LIKED IT <<<<<<<<<<<<<<<<<<<<<

#Easiest and Readable way to Email
#through Python SMTPLIB library
#This works with >>> Gmail.com <<<
import smtplib 
from email.message import EmailMessage

EmailAdd = "Email id" #senders Gmail id over here
Pass = "Email Password" #senders Gmail's Password over here 

msg = EmailMessage()
msg['Subject'] = 'Subject of the Email' # Subject of Email
msg['From'] = EmailAdd
msg['To'] = '[email protected]','[email protected]' # Reciver of the Mail
msg.set_content('Mail Body') # Email body or Content

#### >> Code from here will send the message << ####
with smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp: #Added Gmails SMTP Server
    smtp.login(EmailAdd,Pass) #This command Login SMTP Library using your GMAIL
    smtp.send_message(msg) #This Sends the message