带有正文内容的 Python 电子邮件多部分

2023-07-03Python开发问题
5

本文介绍了带有正文内容的 Python 电子邮件多部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我无法在 python 中发送带有正文的电子邮件作为多部分电子邮件.我所做的一切都导致所有内容都作为附件,我无法让文本或 html 显示在正文中.

I can't send an e-mail in python with a body as a multipart email. Everything I've tried has resulted in all of the content as attachments, and I can't get the text or html to show up in the body.

msg = MIMEMultipart()
if msg_mime_type == 'text' or not msg_mime_type:
    new_body = MIMEText(body, 'text')
elif msg_mime_type == 'image':
    new_body = MIMEImage(body)
elif msg_mime_type == 'html':
    new_body = MIMEText(body, 'html')
new_body.add_header('Content-Disposition', 'inline', filename='body')
msg.set_payload(new_body) #also tried msg.attach(new_body)

我需要使用 Multipart 以便我还可以添加附件,但为了简单起见,我保留了该代码.

I need to use a Multipart so that i can also add attachments, but I kept that code out for simplicity.

推荐答案

您需要指定零件是彼此的替代品,例如multipart/alternative mime 类型:

You need to specify that the parts are alternatives of one another, e.g. the multipart/alternative mime type:

msg = MIMEMultipart('alternative')

默认为混合;请参阅电子邮件库示例.

请注意,要创建包含附件和替代 (HTML/CSS) 选项的电子邮件,您需要有一个包含 alternative<的顶级 multipart/related 容器/code> 部分作为第一个条目.

Note that to create an email with both attachments and an alternative (HTML / CSS) option you'll need to have a top-level multipart/related container that contains the alternative parts as the first entry.

这篇关于带有正文内容的 Python 电子邮件多部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10