How to Send Emails with Python: A Step‑by‑Step Guide Using smtplib
This tutorial walks you through the fundamentals of sending emails with Python, covering SMTP/POP3/IMAP protocols, setting up authorization codes, establishing connections, and constructing plain‑text, HTML, image, and file attachments using the smtplib and email modules.
Introduction
Electronic mail works like a client‑server data exchange using TCP/IP protocols such as SMTP, POP3, and IMAP. Popular services like QQ Mail or NetEase Mail follow the same model.
Preparation
Editor: Sublime Text 3
Required modules: smtplib and
emailInstallation
pip install smtplib pip install emailNote: smtplib is bundled inside the PyEmail package, so you must install PyEmail first.
Enable POP3/SMTP/IMAP and obtain an authorization code
For any mailbox (e.g., QQ Mail), enable the POP3/SMTP/IMAP services in the settings and generate an authorization code using a registered phone number or dynamic token.
Establish a connection
import smtplib sm = smtplib.SMTP() sm.connect('mail_server_address', 'port') # default 25 sm.login('email_account', 'password_or_auth_code') sm.sendmail('[email protected]', '[email protected]', 'message_body') sm.quit()You can also use SSL on port 465 for a secure connection.
Construct email content
1. Text
from email.mime.text import MIMETextUse MIMEText(content, subtype, charset) where subtype can be text/plain or text/html.
MIMEText('hello', 'text/plain', 'utf-8') MIMEText('<a href="www.baidu.com">Click for surprise</a>', 'text/html', 'utf-8')2. Image
from email.mime.image import MIMEImage ff = open('1.jpg', 'rb').read() fd = MIMEImage(ff, 'subtype') fd.add_header('Content-ID', '1.jpg')Images can be embedded in HTML using the cid reference.
3. Multipart (HTML + Image)
from email.mime.multipart import MIMEMultipart msg = MIMEMultipart('related') msg['From'] = '[email protected]' msg['To'] = '[email protected]' msg['Subject'] = 'Subject line' alternative = MIMEMultipart('alternative') msg.attach(alternative) html = """
<html>
<body>
<img src='cid:img' title='I am pig'>
</body>
</html>
"""
alternative.attach(MIMEText(html, 'html', 'utf-8')) ff = open('2.jpg', 'rb') img = MIMEImage(ff.read()) ff.close() img.add_header('Content-ID', '<img>') msg.attach(img) sm.sendmail('[email protected]', '[email protected]', msg.as_string())4. File attachment
msg6 = MIMEMultipart() txt = MIMEText(open('fd.txt', 'rb').read(), 'base64', 'utf-8') txt['Content-Type'] = 'application/octet-stream' txt['Content-Disposition'] = 'attachment; filename="fd.txt"' msg6.attach(txt)The file is now attached and will be delivered with the email.
Debugging
sm.set_debuglevel(1)Enabling debug level prints the full SMTP transaction to the console.
Conclusion
This guide demonstrates how to send plain‑text, HTML, image‑embedded, and file‑attached emails using Python’s standard libraries. By automating email delivery you can create scheduled notifications, reports, or any custom communication, greatly enhancing productivity.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
