用python发带有多个附件的邮件

本文介绍了一种使用Python的smtplib库和email库来发送带有多个附件的电子邮件的方法。通过实例展示了如何连接到SMTP服务器,构造MIME类型的邮件,并将文件作为附件添加到邮件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import os

# 默认发件邮箱为163
def send_email(username,password,subject,from_email,to_email,sender, receiver,dir_path):
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com',25)
    smtp.login(username, password)

    #必须把Subject,From,To,Date添加到MIMEText对象或者MIMEMultipart对象中,邮件中才会显示主题,
    # 发件人,收件人,时间(若无时间,就默认一般为当前时间,该值一般不设置)
    msg = MIMEMultipart('mixed')
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = to_email

    text_plain = MIMEText(text, 'plain', 'utf-8')
    msg.attach(text_plain)

    # 获取查询结果目录
    fileName_list = os.listdir(dir_path)
    filePath_list = [os.path.join(dir_path, imageName) for imageName in fileName_list]
    print(filePath_list)

    # 添加多个附件
    if len(filePath_list) != 0:
        for i in range(len(filePath_list)):
            if os.path.isfile(filePath_list[i]):
                att = MIMEText(open(filePath_list[i], 'rb').read(), 'base64', 'utf-8')
                att["Content-Type"] = 'application/octet-stream'
                # att["Content-Disposition"] = "attachment; filename=%s"%filePath_list[i] 附件名不能为中文
                att.add_header("Content-Disposition", "attachment", filename=("gbk", "", "%s"%filePath_list[i]))  # 附件名可以为中文
                msg.attach(att)

    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()

# ------------------------------------------------------------------------------
username = "******"   # 用于登录的用户名
password = "******"   # 用于登录的密码,网易的网页版是授权码非密码
sender = "******"  # 发件地址
receiver = "******"  # 收件地址
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"  # 邮件中的正文
subject = 'Python email test'  # 邮件名字
from_email = '******'  # 邮件中显示的发件人
to_email = '******'  # 邮件中显示的收件人
dir_path = r'D:\report'  # 需要添加到附件的目录
# 调用
send_email(username,password,subject,from_email,to_email,sender, receiver,dir_path)


# ------------------------------------------------------------------------------------
# host:指定连接的邮箱服务器。常用邮箱的smtp服务器地址如下:
# 新浪邮箱:smtp.sina.com,新浪VIP:smtp.vip.sina.com,搜狐邮箱:smtp.sohu.com,126邮箱:smtp.126.com,139邮箱:smtp.139.com,163网易邮箱:smtp.163.com。
# port:指定连接服务器的端口号,默认为25.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值