Replacing cid src with base64



假设我有HTML(实际上是一封电子邮件(,其中包含多个带有cid:reference的<img>。我想要一些python代码将它们逐个替换为原始图像的base64版本。我知道如何获得图像并对其进行base64编码,但我如何用特定的其他字符串(图像的编码变体(替换字符串的子集。。。

replace(A,B(只是把所有的东西都替换成同一个东西。。。有人能帮我思考吗?(

样本输入:

><a href="https://urlshortener.teams.microsoft.com/8D8660148021F90-7-11" style="text-decoration:none">&nbsp;&nbsp;&nbsp;</a></td><td valign="middle" style="vertical-align:middle; font-size:0"><a href="https://urlshortener.teams.microsoft.com/8D8660148021F90-7-10" style="text-decoration:none"><img height="16" width="14" style="vertical-align:middle; height:16px; width:14px" data-outlook-trace="F:1|T:1" src="cid:9A5CA00DCF7842D99534F2F486FB7E5A"></a></td><td valign="middle" width="5" style="width:5px"><a href="https://urlshortener.teams.microsoft.com/8D8660148021F90-7-9" style="text-decoration:none">&nbsp;&nbsp;&nbsp;</a></td><td valign="middle"><a href="https://urlshortener.teams.microsoft.com/8D8660148021F90-7-8" style="vertical-al

如果src=被取代,那么输出就是全部

src="data:image/png;base64, <!-- base64encoded picture -->"

以及源字符串(html(中的每个相应图像。

非常感谢!

如果有人需要的话。在@Andrej Kesely的帮助下,如果构建了这个解决方案:

@login_required
def get_mail(request):
message = Message.objects.get(pk=int(request.POST['id']))
html = message.html
.replace('<pre', '<code style="white-space: line-wrap;"')
.replace('</pre', '</code>')
for pic in re.finditer(r'cid:([^"]+)', html):
attm = MessageAttachment.objects.get(message=message, headers__contains=pic[1])
b64 = base64.b64encode(open('/media/' + str(attm.document), 'rb').read()).decode('utf-8')
html = re.sub(r'src=".+"', f'src="data:image/jpeg;base64, {b64}"', html)
return render(request, "message.j2.html", {'message': message, 'html': html})

最新更新