python smtplib multipart email body not showing on iphone

不打扰是莪最后的温柔 提交于 2019-12-08 07:54:37

问题


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:


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()


来源:https://stackoverflow.com/questions/23420690/python-smtplib-multipart-email-body-not-showing-on-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!