【问题标题】:How to add images embedded in the body of the email with python?如何使用python添加嵌入在电子邮件正文中的图像?
【发布时间】:2020-02-03 12:16:07
【问题描述】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 2013-08-31
      • 2016-09-07
      • 2014-10-03
      • 1970-01-01
      相关资源
      最近更新 更多