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

Python如何使用邮件发送附件

Python可以使用smtplib和email库来发送带附件的邮件。下面是一个示例代码:

代码语言:txt
复制
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_email, sender_password, receiver_email, subject, body, attachment_path):
    # 创建邮件对象
    message = MIMEMultipart()
    message["From"] = sender_email
    message["To"] = receiver_email
    message["Subject"] = subject

    # 添加正文
    message.attach(MIMEText(body, "plain"))

    # 添加附件
    with open(attachment_path, "rb") as attachment:
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header("Content-Disposition", f"attachment; filename= {attachment_path}")
        message.attach(part)

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

# 使用示例
sender_email = "your_email@example.com"
sender_password = "your_password"
receiver_email = "recipient@example.com"
subject = "邮件主题"
body = "邮件正文"
attachment_path = "path_to_attachment_file"

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

在上面的代码中,需要替换以下变量:

  • sender_email:发件人邮箱地址
  • sender_password:发件人邮箱密码
  • receiver_email:收件人邮箱地址
  • subject:邮件主题
  • body:邮件正文
  • attachment_path:附件文件路径

这段代码使用SMTP协议发送邮件,需要替换smtp.example.com为你的邮件服务器的地址和端口号。请确保你的发件人邮箱开启了SMTP服务。

推荐的腾讯云相关产品是腾讯企业邮,它提供了稳定可靠的企业级邮件服务。你可以在腾讯云官网上找到更多关于腾讯企业邮的信息和产品介绍:腾讯企业邮

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

相关·内容

领券