Python Script for Sending Emails with Attachments Using smtplib

This article presents a concise Python example that demonstrates how to compose and send an email with a text body and a file attachment via the smtplib library, including MIME construction, encoding, and SMTP authentication steps.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Script for Sending Emails with Attachments Using smtplib

The snippet provides a straightforward Python program that creates a multipart email, attaches a plain‑text body and a file, encodes the attachment, and sends the message through an SMTP server using the smtplib library.

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

user = '[email protected]'  # sender email address
pwd = 'xxxxxx'       # sender password
to = ['[email protected]']  # recipient list (can contain multiple addresses)
msg = MIMEMultipart()
msg['Subject'] = '这里是主题...'
content1 = MIMEText('这里是正文!', 'plain', 'utf-8')
msg.attach(content1)
attfile = 'XXXXXXXX/test.txt' # file path of the attachment
basename = os.path.basename(attfile)
fp = open(attfile, 'rb')
att = MIMEText(fp.read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', basename))
encoders.encode_base64(att)
msg.attach(att)
# -----------------------------------------------------------
s = smtplib.SMTP('smtp.exmail.qq.com')
s.login(user, pwd)
s.sendmail(user, to, msg.as_string())
print('发送成功')
s.close()

At the end of the article, a QR code is provided for readers to obtain additional resources on automated interface testing.

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.

Pythonbackend-developmentattachmentSMTP
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

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.