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

使用Python通过电子邮件发送附件

可以通过SMTP(Simple Mail Transfer Protocol)库来实现。SMTP库是Python内置的标准库,可以用于发送电子邮件。

以下是一个示例代码,演示如何使用Python发送带有附件的电子邮件:

代码语言: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(sender_email, sender_password, receiver_email, subject, message, attachment_path):
    # 创建一个带附件的邮件实例
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject

    # 添加邮件正文
    msg.attach(MIMEText(message, 'plain'))

    # 添加附件
    attachment = open(attachment_path, 'rb')
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % attachment_path)
    msg.attach(part)

    # 连接SMTP服务器并发送邮件
    server = smtplib.SMTP('smtp.example.com', 587)  # 替换为你的SMTP服务器地址和端口号
    server.starttls()
    server.login(sender_email, sender_password)
    server.sendmail(sender_email, receiver_email, msg.as_string())
    server.quit()

# 使用示例
sender_email = 'your_email@example.com'  # 发件人邮箱
sender_password = 'your_password'  # 发件人邮箱密码
receiver_email = 'recipient_email@example.com'  # 收件人邮箱
subject = '邮件主题'  # 邮件主题
message = '邮件正文'  # 邮件正文
attachment_path = 'path_to_attachment'  # 附件路径

send_email(sender_email, sender_password, receiver_email, subject, message, attachment_path)

在上述代码中,需要替换以下内容:

  • smtp.example.com:SMTP服务器地址和端口号,根据你的邮件提供商进行替换。
  • your_email@example.com:发件人邮箱地址。
  • your_password:发件人邮箱密码。
  • recipient_email@example.com:收件人邮箱地址。
  • 邮件主题:邮件的主题。
  • 邮件正文:邮件的正文内容。
  • path_to_attachment:附件的路径。

此外,你还需要确保你的Python环境中已经安装了smtplib库。

这是一个使用Python通过电子邮件发送附件的示例。你可以根据自己的需求进行修改和扩展。

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

相关·内容

领券