在 Python 中,最稳定和常用的第三方库用于发送邮件附件是 smtplib、email 和 MIMEText。这些库都是 Python 的标准库,并且有广泛的使用和支持。以下是一个使用这些库发送邮件附件的示例代码:

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

def send_email_with_attachment(sender, receiver, subject, body, attachment):
    # 创建一个多部分(multipart)的邮件对象
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = subject

    # 添加正文
    msg.attach(MIMEText(body, 'plain'))

    # 添加附件
    with open(attachment, 'rb') as file:
        attachment_data = file.read()
    attachment_part = MIMEText(attachment_data, 'base64', 'utf-8')
    attachment_part['Content-Type'] = 'application/octet-stream'
    attachment_part.add_header('Content-Disposition', 'attachment', filename=attachment)
    msg.attach(attachment_part)

    # 发送邮件
    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.ehlo()
        server.starttls()
        server.login('username', 'password')
        server.sendmail(sender, receiver, msg.as_string())

# 使用示例
sender = 'sender@example.com'
receiver = 'receiver@example.com'
subject = 'Test Email with Attachment'
body = 'This is a test email with attachment.'
attachment = 'path/to/attachment.pdf'

send_email_with_attachment(sender, receiver, subject, body, attachment)

请注意,这只是一个示例,并且需要替换为您自己的发件人、收件人、SMTP服务器和认证信息。确保您已经安装了相应的库,可以通过运行pip install smtplib email命令来安装它们。

Python 发送邮件附件:最稳定第三方库和代码示例

原文地址: https://www.cveoy.top/t/topic/phQe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录