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

How to add images embedded in the body of the email with python?

这是我目前的代码,在 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)

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

        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}'