~/python/python-smtp-how-send-html-email-code-smtp-server-authentication.md

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

1 min readJune 15, 2022by Gorav Singal#python#python-3#smtp
// TL;DR

Use Python's smtplib and email.mime modules to send HTML emails through an authenticated SMTP server with TLS encryption.

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

Introduction

This post has the complete code to send email through smtp server, with authentication.

Requirements

We need following parameters:

  • SMTP Server host address
  • SMTP Server port
  • Sender Email
  • Sender Email Credentials

from smtplib import SMTP_SSL as SMTP
from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

class EmailClient:
  def __init__(self):
    self._mail_server = '<Your-email-smtp-server>'
    self._mail_server_port = 587 # <smtp-server port number>
    self._sender = "<sender email address>"
    self._credentials = {
      "username": "<sender email address>",
      "password": "<password>"
    }

  def send_mail(self, recipients, subject, email_body):    
    msg = MIMEMultipart()
    body = MIMEText(email_body, 'html')
    msg['Subject'] = subject
    msg.attach(body)

    with SMTP(self._mail_server,port=self._mail_server_port) as conn:
      conn.login(self._credentials['username'], self._credentials['password'])

      conn.sendmail(self._sender, recipients, msg.as_string())

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Python SMTP Email Code - Sender Address Rejected - Not Owned By User

Python SMTP Email Code - Sender Address Rejected - Not Owned By User

Introduction In a normal email sending code from python, I’m getting following…

Implementation of Timeit function, Get performance numbers for a function

Implementation of Timeit function, Get performance numbers for a function

This is regarding the timeit implementation in python. The basic requirement…

Python: How to generate string of arbitrary length of any alphabet characters

Python: How to generate string of arbitrary length of any alphabet characters

I was testing a bug where a field was limited to 255 characters only. I needed…

Python Build Quality Gates with Pylint and Unittest Coverage Thresholds

Python Build Quality Gates with Pylint and Unittest Coverage Thresholds

Introduction It is very important to introduce few process so that your code and…

Python - How to Implement Timed-Function which gets Timeout After Specified Max Timeout Value

Python - How to Implement Timed-Function which gets Timeout After Specified Max Timeout Value

Introduction We often require to execute in timed manner, i.e. to specify a max…

How to Solve Circular Import Error in Python

How to Solve Circular Import Error in Python

Introduction To give some context, I have two python files. (Both in same folder…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…