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

如何使用Python 3.6发送电子邮件附件

使用Python 3.6发送电子邮件附件可以通过使用内置的smtplib和email库来实现。下面是一个完整的示例代码:

代码语言:python
复制
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, 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', f"attachment; filename= {attachment_path}")
    msg.attach(part)

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

# 使用示例
sender_email = "your_email@gmail.com"
sender_password = "your_password"
receiver_email = "recipient_email@example.com"
subject = "Sample Email with Attachment"
message = "This is a sample email with attachment."
attachment_path = "path_to_attachment_file"

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

上述代码中,需要替换以下变量的值:

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

这段代码使用Gmail的SMTP服务器发送邮件,如果你使用其他邮箱提供商,请相应地更改SMTP服务器的地址和端口号。

推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/etp

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

相关·内容

1分17秒

Python进阶如何修改闭包内使用的外部变量?

4分39秒

看我如何使用Python对行程码与健康码图片文字进行识别统计

4分47秒

Flink 实践教程-入门(10):Python作业的使用

4分47秒

Flink 实践教程:入门(10):Python 作业的使用

2分53秒

HiFlow延迟执行怎么玩

4分31秒

016_如何在vim里直接运行python程序

589
7分53秒

EDI Email Send 与 Email Receive端口

1分56秒

有点意思,433MHz自发电无线开关

45秒

工程监测多通道振弦传感器无线采发仪该如何选择

2分7秒

基于深度强化学习的机械臂位置感知抓取任务

17分43秒

MetPy气象编程Python库处理数据及可视化新属性预览

47秒

工程监测多通道振弦模拟信号采集仪VTN如何OEM定制呢

领券