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.
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.
Test Development Learning Exchange
Test Development Learning Exchange
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.