首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在python中找不到要将文件作为附件发送的文件

在Python中,要将文件作为附件发送,可以使用smtplib和email库来实现。以下是一个示例代码:

代码语言:txt
复制
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

def send_email_with_attachment(sender_email, sender_password, receiver_email, subject, body, attachment_path):
    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject

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

    # 添加附件
    with open(attachment_path, 'rb') as file:
        attachment = MIMEApplication(file.read())
        attachment.add_header('Content-Disposition', 'attachment', filename=attachment_path)
        msg.attach(attachment)

    # 发送邮件
    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login(sender_email, sender_password)
        server.send_message(msg)

# 使用示例
sender_email = 'sender@example.com'
sender_password = 'password'
receiver_email = 'receiver@example.com'
subject = 'Email with Attachment'
body = 'Please find the attached file.'
attachment_path = 'path/to/file.txt'

send_email_with_attachment(sender_email, sender_password, receiver_email, subject, body, attachment_path)

在上述代码中,我们使用smtplib库来连接SMTP服务器,并使用email库来构建邮件对象。首先,我们创建一个MIMEMultipart对象作为邮件容器,然后设置发件人、收件人和主题。接下来,我们使用MIMEText添加邮件正文。然后,我们打开要发送的文件,创建一个MIMEApplication对象,并将文件内容添加到附件中。最后,我们使用smtplib库连接SMTP服务器,登录发件人邮箱,并发送邮件。

这是一个简单的示例,你可以根据实际需求进行修改和扩展。如果你想了解更多关于Python邮件发送的内容,可以参考腾讯云的产品文档:腾讯云邮件推送(SMTP)

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券