Search code examples
pythonpython-3.xmime-typesemail-attachments

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


This is my code at the moment, in outlook it works fine, but GMail shows my images as attachments and does not show embedded. What am I doing wrong?

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)

Solution

  • Problem solved! After a lot of research, I managed to find the solution!

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