用于发送带有附件的邮箱的Python脚本正在运行,但所有附件(如果有的话)都是以.eml文件而不是jpg、pdf、txt等格式到达的.它们确实可以正确打开,但我更希望它们带有实际的名称和类型.虽然我对Python3(attach( changed to add_attachment()做了一些小的更改,但它在我的Python2.7上确实起作用了.

此外,我不断地遇到这样的引用,即set_payload已被弃用,但我看不到应该使用什么来代替.

# Attach any files
files = '''/Users/Mine/Desktop/RKw.jpeg\n/Users/Mine/Desktop/PG_2022.pdf'''.splitlines()
for file in files:
    attachment = open(file, "rb")
    part = MIMEBase("application", "octet-stream")
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header("Content-Disposition", f"attachment; filename= {file.split('/')[-1]}")
    msg.add_attachment(part)

推荐答案

您可以将附加文件的filename and the content type amongst other options的选项传递给add_attachment.

def get_ctype(filepath):
    ctype, encoding = mimetypes.guess_type(filepath)
    if ctype is None or encoding is not None:
       ctype = 'application/octet-stream'
    return ctype

# Attach any files
files = '''/Users/Mine/Desktop/RKw.jpeg\n/Users/Mine/Desktop/PG_2022.pdf'''.splitlines()
for file in files:
    attachment = open(file, "rb")
    ctype = get_ctype(file)
    maintype, subtype = ctype.split('/', 1)

    msg.add_attachment(
        attachment.read(),
        maintype=maintype,
        subtype=subtype,
        filename=file.split('/')[-1],    
    )

Python相关问答推荐

将DF中的名称与另一DF拆分并匹配并返回匹配的公司

如何使用html从excel中提取条件格式规则列表?

Mistral模型为不同的输入文本生成相同的嵌入

Julia CSV for Python中的等效性Pandas index_col参数

使用groupby Pandas的一些操作

django禁止直接分配到多对多集合的前端.使用user.set()

利用Selenium和Beautiful Soup实现Web抓取JavaScript表

NumPy中条件嵌套for循环的向量化

导入...从...混乱

将pandas导出到CSV数据,但在此之前,将日期按最小到最大排序

无论输入分辨率如何,稳定扩散管道始终输出512 * 512张图像

try 检索blob名称列表时出现错误填充错误""

matplotlib图中的复杂箭头形状

在matplotlib中使用不同大小的标记顶部添加批注

Gekko中基于时间的间隔约束

当条件满足时停止ODE集成?

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名

为什么在生成时间序列时,元组索引会超出范围?

Pandas:使列中的列表大小与另一列中的列表大小相同

大Pandas 每月重新抽样200万只和300万只