python smtplib multipart email body not showing on iphone

Question:

I am trying to send an email with an image using smtplib in python. The email shows up fine on my desktop and on the iphone gmail app, but on the standard iphone mail app the body doesn’t appear. Here is my code:

    def send_html_email(self, subject, html, to_email,from_email, password, from_name, image=None):
        msg = MIMEMultipart('alternative')
        msg['From'] = from_name
        msg['To'] = to_email
        msg['Subject'] = subject

        html_message = MIMEText(html, "html")
        msg.attach(html_message)

        if image:
            msgImage = MIMEImage(image)
            msgImage.add_header('Content-ID', '<image1>')
            msg.attach(msgImage)

        session = smtplib.SMTP("smtp.gmail.com:587")
        session.starttls()
        session.login(from_email, password)
        session.sendmail(from_email, to_email, msg.as_string().encode('utf-8'))
        session.quit()

It seems that when I do not add an image, the email sends fine with the body. Any ideas on how to get it working with the image as well?

Asked By: Atul Bhatia

||

Answers:

This appears to work:

def send_html_email(self, subject, html, to_email, from_email, password, from_name, image=None):
    msgRoot = MIMEMultipart('related')
    msgRoot['From'] = from_name
    msgRoot['To'] = to_email
    msgRoot['Subject'] = subject
    msg = MIMEMultipart('alternative')
    msgRoot.attach(msg)
    html_message = MIMEText(html, "html")
    msg.attach(html_message)

    if image:
        msgImage = MIMEImage(image)
        msgImage.add_header('Content-ID', '<image1>')
        msgRoot.attach(msgImage)

    session = smtplib.SMTP("smtp.gmail.com:587")
    session.starttls()
    session.login(from_email, password)
    session.sendmail(from_email, to_email, msgRoot.as_string().encode('utf-8'))
    session.quit()
Answered By: Atul Bhatia

There’s a really good post with multiple solutions to this problem here. I was able to send an email with HTML, an Excel attachment, and an embedded images.

Answered By: JoshuaHew