简体   繁体   English

如何在邮件中附加图像文件和嵌入到 html 电子邮件正文的相同图像?

[英]How can I attach image files and same image embedded to html email body in a mail?

I can only attach image files but embedded image files doesn't appears in the mail .我只能附加图像文件,但嵌入的图像文件不会出现在邮件中。 It says The link image cannot be displayed file may be removed, deleted or renamed.它说无法显示链接图像文件可能会被删除、删除或重命名。 verify link point to correct image file and location and also files attached are of same size.验证链接指向正确的图像文件和位置,并且附加的文件大小相同。 below is the code which I used下面是我使用的代码

from requests_toolbelt import MultipartEncoder
import requests
import smtplib
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
from os.path import basename
from jinja2 import Template

def send_mail(send_from: str, subject: str, text: str,send_to: list, files= None):

    send_to= default_address if not send_to else send_to
    main = Template('''
    <html><body>
    {% for image in pictures %}<img src="cid:{{image}}">{% endfor %}
    </body></html>''')  
    msg = MIMEMultipart()
    html = main.render(pictures=files)
    part2 = MIMEText(html, 'html')
    msg.attach(part2)
    msg['From'] = send_from
    msg['To'] = ', '.join(send_to)
    msg['Subject'] = subject
    for f in files or []:
        with open(f, "rb") as fil:
            msgImage = MIMEImage(fil.read())
            ext = f.split('.')[-1:]
            attachedfile = MIMEApplication(fil.read(), _subtype = ext)
            fil.close()
            msgImage.add_header('Content-ID', '<{}>'.format(f))
            msgImage.add_header('content-Disposition','inline',filename=f)
            msg.attach(msgImage)
            attachedfile.add_header(
                'content-disposition', 'attachment', filename=basename(f) )
        msg.attach(msgImage)
        msg.attach(attachedfile)
    smtp = smtplib.SMTP(host="smtp-mail.outlook.com", port= 25)
    smtp.starttls()
    smtp.login(usr,pwd)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
send_mail(send_from= frommail,
subject="Daily backup Testing",
text='files added: ',
send_to= tomail,
files= files_list)

I get mail as this我收到这样的邮件截屏 . . Image path files are correct.图像路径文件正确。 when I print I get this files ['check123\\\\Screenshot (161).png', 'check123\\\\Screenshot (163).png', 'check123\\\\Screenshot (164).png'] How can I solve this issue?当我打印我得到这个files ['check123\\\\Screenshot (161).png', 'check123\\\\Screenshot (163).png', 'check123\\\\Screenshot (164).png']我该如何解决这个问题?

The file names are not particularly suitable as cid: identifiers.文件名不是特别适合作为cid:标识符。 In particular, the backslashes and parentheses are not valid in cid: identifiers.特别是,反斜杠和括号在cid:标识符中无效。 See also What are the valid characters for a Mime Multipart message ContentId "CID:"?另请参阅Mime 多部分消息 ContentId "CID:" 的有效字符是什么?

Maybe just generate unique random identifiers from a constrained set of characters and map them to your file names instead.也许只是从一组受限制的字符中生成唯一的随机标识符,然后将它们映射到您的文件名。

Off the top of my head (untested),在我的头顶(未经测试),

import random # in addition to the other imports you have
import string

# cribbed from https://stackoverflow.com/a/2030081/874188
def random_cid ():
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(10))

def send_mail(send_from: str, subject: str, text: str,send_to: list, files= None):

    send_to= default_address if not send_to else send_to

    cid_map = { x: random_cid() for x in files }
    main = Template('''
    <html><body>
    {% for image in pictures %}<img src="cid:{{cid_map[image]}}">{% endfor %}
    </body></html>''')
    msg = MIMEMultipart()
    html = main.render(pictures=files, cid_map=cid_map)
    part2 = MIMEText(html, 'html')  
    # ...
    for f in files:
        with open(f, "rb") as fil:
            msgImage = MIMEImage(fil.read())
            ext = f.split('.')[-1:]
            attachedfile = MIMEApplication(fil.read(), _subtype = ext)
            fil.close()
            msgImage.add_header('Content-ID', '<{}>'.format(cid_map[f]))
            msgImage.add_header('content-Disposition','inline',filename=f)
            msg.attach(msgImage)
            attachedfile.add_header(
                'content-disposition', 'attachment', filename=basename(f) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM