Skip to content

Instantly share code, notes, and snippets.

Created June 15, 2018 07:57
What would you like to do?
Sending email using python and gmail
# import dependencies
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import email
import email.mime.application
from django.utils.html import strip_tags
# create message
msg = MIMEMultipart('alternative')
msg['Subject'] = "Test Mail : ThePythonDjango.Com"
msg['From'] = ""
msg['To'] = ""
# create body
html_text = '<div style="border:1px solid black">This is your message body in HTML format.</div>'
plain_text = strip_tags(html_text)
# Create the body of the message (a plain-text and an HTML version).
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(plain_text, 'plain')
part2 = MIMEText(html_text, 'html')
# Attach image if any
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
# Send the message via local SMTP server.
host = ""
port = 587
mail = smtplib.SMTP(host, port, timeout=60)
# Add recepiens, cc or bcc if any
recepient = [msg["To"]]
# username and password of gmail id which will be used to send email
username = "your-user-name"
password = "*****"
# login using credentials
mail.login(username, password)
# send email
mail.sendmail(msg["From"], recepient, msg.as_string())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment