使用python的smtplib实现带附件邮件群发,核心在于构建包含多个部分的mime消息体并调用sendmail方法。你需要实例化mimemultipart对象,依次添加文本内容、html内容以及通过mimebase类处理的附件文件,最后将组装好的消息体转换为字符串发送给收件人列表。

如何正确构建包含多种类型的MIME消息体
构建消息体的关键在于按顺序添加不同部分,并确保每个部分都有正确的MIME类型和编码方式。通常先创建MIMEMultipart混合类型对象,然后分别创建MIMEText用于纯文本和HTML内容,再创建MIMEBase用于处理二进制附件。对于附件,需要读取文件内容并设置Content-Disposition头以指定文件名。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def send_email_with_attachment(sender, password, recipients, subject, body, html_body, attachment_path):
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = ', '.join(recipients)
msg['Subject'] = subject
# 添加纯文本部分
msg.attach(MIMEText(body, 'plain'))
# 添加HTML部分
msg.attach(MIMEText(html_body, 'html'))
# 添加附件
with open(attachment_path, 'rb') as f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename= {attachment_path.split("/")[-1]}')
msg.attach(part)
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(sender, password)
server.sendmail(sender, recipients, msg.as_string())
server.quit()
# 示例调用
recipients_list = ['user1@example.com', 'user2@example.com']
send_email_with_attachment(
sender='myaccount@example.com',
password='mypassword',
recipients=recipients_list,
subject='Test Email',
body='This is the plain text body.',
html_body='<b>This is the HTML body.</b>',
attachment_path='/path/to/file.pdf'
)如何处理群发时的收件人列表与发送状态
在群发场景下,需要将收件人列表作为数组传递给sendmail方法的第二个参数。该方法会尝试向列表中的每个地址发送邮件,如果某个地址发送失败,通常会抛出异常。为了更稳健地处理群发,可以遍历收件人列表逐个发送,或者捕获异常并记录失败的地址,以便后续重试或通知。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;

import smtplib
from email.mime.text import MIMEText
def send_bulk_emails(sender, password, recipients, subject, body):
failed_recipients = []
for recipient in recipients:
try:
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(sender, password)
server.sendmail(sender, [recipient], msg.as_string())
server.quit()
print(f"Email sent to {recipient}")
except smtplib.SMTPException as e:
failed_recipients.append(recipient)
print(f"Failed to send to {recipient}: {str(e)}")
if failed_recipients:
print(f"Failed recipients: {failed_recipients}")
# 示例调用
recipients_list = ['user1@example.com', 'invalid_user', 'user2@example.com']
send_bulk_emails(
sender='myaccount@example.com',
password='mypassword',
recipients=recipients_list,
subject='Bulk Test',
body='This is a bulk email test.'
)当附件路径不存在时程序会抛出什么异常
当附件路径不存在时,程序在尝试打开文件进行读取时会抛出FileNotFoundError异常。这是因为代码中使用了open函数来读取附件文件,如果指定的路径无效或文件不存在,Python会立即中断执行并抛出该异常。为了避免这种情况,应在打开文件前检查文件是否存在,或者使用try-except块来捕获并处理这个特定的异常。

















