python smtplib multipart email body not showing on

2019-05-31 17:46发布

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?

1条回答
贼婆χ
2楼-- · 2019-05-31 18:12

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()
查看更多
登录 后发表回答