这个问题实际上是这个答案的延续

我想这样做,我通过一个图像列表循环,此外,每个图像旁边会有不同的文本.Something like this for example as you can see in Weather Next 10 days我想循环浏览文件夹中的图像,每个图像旁边都会有一些不同的文本,如示例所示.

from email.message import EmailMessage
from email.utils import make_msgid
import mimetypes

msg = EmailMessage()

# generic email headers
msg['Subject'] = 'Hello there'
msg['From'] = 'ABCD <abcd@example.com>'
msg['To'] = 'PQRS <pqrs@example.org>'

# set the plain text body
msg.set_content('This is a plain text body.')

# now create a Content-ID for the image
image_cid = make_msgid(domain='example.com')
# if `domain` argument isn't provided, it will 
# use your computer's name

# set an alternative html body
msg.add_alternative("""\
<html>
    <body>
        <p>This is an HTML body.<br>
           It also has an image.
        </p>
        <img src="cid:{image_cid}">
    </body>
</html>
""".format(image_cid=image_cid[1:-1]), subtype='html')
# image_cid looks like <long.random.number@example.com>
# to use it as the img src, we don't need `<` or `>`
# so we use [1:-1] to strip them off


# now open the image and attach it to the email
with open('path/to/image.jpg', 'rb') as img:

    # know the Content-Type of the image
    maintype, subtype = mimetypes.guess_type(img.name)[0].split('/')

    # attach it
    msg.get_payload()[1].add_related(img.read(), 
                                         maintype=maintype, 
                                         subtype=subtype, 
                                         cid=image_cid)


# the message is ready now
# you can write it to a file
# or send it using smtplib

推荐答案

如果我能猜出你想问什么,解决方案就是 for each 图像生成一个唯一的cid.

from email.message import EmailMessage
from email.utils import make_msgid
# import mimetypes

msg = EmailMessage()

msg["Subject"] = "Hello there"
msg["From"] = "ABCD <abcd@example.com>"
msg["To"] = "PQRS <pqrs@example.org>"

# create a Content-ID for each image
image_cid = [make_msgid(domain="example.com")[1:-1],
    make_msgid(domain="example.com")[1:-1],
    make_msgid(domain="example.com")[1:-1]]

msg.set_content("""\
<html>
    <body>
        <p>This is an HTML body.<br>
           It also has three images.
        </p>
        <img src="cid:{image_cid[0]}"><br/>
        <img src="cid:{image_cid[1]}"><br/>
        <img src="cid:{image_cid[2]}">
    </body>
</html>
""".format(image_cid=image_cid), subtype='html')

for idx, imgtup in enumerate(
        ("path/to/first.jpg", "jpeg"),
        ("file/name/of/second.png", "png"),
        ("path/to/third.gif", "gif")):
    imgfile, imgtype = imgtup
    with open(imgfile, "rb") as img:
        msg.get_payload()[0].add_related(
            img.read(), 
            maintype="image", 
            subtype=imgtype, 
            cid=f"<{image_cid[idx]}>")

# The message is ready now.
# You can write it to a file
# or send it using smtplib

使用现代EmailMessage API的荣誉;我们仍然看到太多问题,盲目地从Python复制/粘贴旧API<;=3.5带MIMEMultipart等.

我go 掉了mimetypes个图像格式查询逻辑,以便在代码中拼写出每个图像的类型.如果您需要Python进行猜测,您知道如何进行猜测,但对于一个小的静态图像列表,只指定每个图像似乎更有意义,并避免开销以及启发式猜测错误这一不太可能但并非不可能的问题.

我猜你们的图片都会使用相同的格式,所以实际上你们可以简单地硬编码subtype="png"或者其他什么.

如何向循环图像元组中添加更多的每图像信息应该是显而易见的,尽管如果您的需求超出了琐碎的范围,您可能会希望将图像及其各种属性封装到一个简单的类中.

对于无法访问HTML部分的收件人来说,您的消息显然毫无意义,因此我go 掉了您的伪text/plain部分.你实际上是在向那些喜欢通过HTML查看纯文本的收件人发送一条完全不同的消息;如果这真的是你的意图,请停止它.如果你不能像HTML版本那样以纯文本版本提供same条信息,至少不要让收件人觉得你一开始没有什么重要的话要说.

切记,请不要伪造你不拥有的域名的邮箱地址.你最终会向垃圾邮件发送者告密,让他们试图向无辜的第三方发送未经请求的消息.始终使用IANA保留域,如example.comexample.org等,这些域保证在现实中永远不存在.我编辑了你的问题来解决这个问题.

Python相关问答推荐

2维数组9x9,不使用numpy.数组(MutableSequence的子类)

比较两个数据帧并并排附加结果(获取性能警告)

Python上的Instagram API:缺少client_id参数"

如何获取numpy数组的特定索引值?

ODE集成中如何终止solve_ivp的无限运行

基于索引值的Pandas DataFrame条件填充

当我try 在django中更新模型时,模型表单数据不可见

Plotly Dash Creating Interactive Graph下拉列表

如何启动下载并在不击中磁盘的情况下呈现响应?

如何使用SentenceTransformers创建矢量嵌入?

Maya Python脚本将纹理应用于所有对象,而不是选定对象

干燥化与列姆化的比较

如果包含特定值,则筛选Groupby

python的文件. truncate()意外地没有截断'

在第一次调用时使用不同行为的re. sub的最佳方式

如何获取包含`try`外部堆栈的`__traceback__`属性的异常

Polars表达式无法访问中间列创建表达式

如何在不遇到IndexError的情况下将基数10的整数转换为基数80?

更新包含整数范围的列表中的第一个元素

如何使用count()获取特定日期之间的项目