如何使用python添加嵌入电子邮件正文的图像?

问题描述 投票:0回答:1

这是目前的代码,在Outlook中它可以正常工作,但是GMail将我的图像显示为附件,而不显示为嵌入式。我在做什么错?

class RawMailHelper:
def montarRawMail(self, emailSimples):
    CHARSET = "utf-8"
    msg = MIMEMultipart('mixed')

    msg['Subject'] = emailSimples['Message']['Subject']['Data']
    msg['From'] = emailSimples['Source']
    msg['To'] = ','.join(emailSimples['Destination']['ToAddresses'])

    soup = BeautifulSoup(emailSimples['Message']['Body']['Html']['Data'])
    i = 1

    for img in soup.findAll('img'):
        imgInBase64 = img['src'].split(',')[1]
        imgData = base64.b64decode(imgInBase64)

        imgType = imghdr.what(file=f'image{i}', h=imgData)

        att = MIMEImage(imgData)
        att.add_header('Content-ID', f'image{i}')
        att['Content-Disposition'] = f'inline; filename=image{i}.{imgType}'
        msg.attach(att)

        img['src'] = f'cid:image{i}'

        i += 1

    corpoHtml = str(soup)

    textpart = MIMEText(emailSimples['Message']['Body']['Text']['Data'], 'plain', CHARSET)
    htmlpart = MIMEText(corpoHtml, 'html', CHARSET)

    msg_body = MIMEMultipart('alternative')
    msg_body.attach(textpart)
    msg_body.attach(htmlpart)

    msg.attach(msg_body)
python python-3.x mime-types email-attachments
1个回答
1
投票

问题解决了!经过大量研究,我设法找到了解决方案!

        att = MIMEImage(imgData)
        att.add_header('Content-ID', f'<image{i}.{imgType}>')
        att.add_header('X-Attachment-Id', f'image{i}.{imgType}')
        att['Content-Disposition'] = f'inline; filename=image{i}.{imgType}'
        msg.attach(att)

        img['src'] = f'cid:image{i}.{imgType}'
© www.soinside.com 2019 - 2024. All rights reserved.