How to Send Emails Using Python's smtplib and email Modules

This tutorial explains how to configure an email account, connect to an SMTP server with Python's smtplib, construct plain‑text, HTML, and attachment‑based messages using the email.mime library, and send them programmatically, providing complete code examples for each step.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
How to Send Emails Using Python's smtplib and email Modules

SMTP (Simple Mail Transfer Protocol) is a protocol for sending emails; Python's smtplib provides a convenient wrapper.

First, obtain an email account and its authorization code (e.g., QQ mail). Then connect to the SMTP server using

import smtplib
con = smtplib.SMTP_SSL('smtp.163.com', 465)

and log in with con.login('[email protected]', 'auth_code').

Construct the email using the email.mime package: create a MIMEMultipart() object, set the subject with Header, specify the sender and recipients, and attach content. For plain‑text messages, attach a MIMEText(content, 'plain', 'utf-8') object; for HTML messages, attach a MIMEText(html_content, 'html', 'utf-8') object.

Send the message with con.sendmail(sender, recipients, msg.as_string()) and close the connection with con.quit().

To add attachments, create a MIMEText (or MIMEImage) object with the file data encoded as base64, set its Content‑Disposition to attachment; filename="file.ext", attach it to the message, and then send as above.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendSMTPsmtplibemail-sending
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.