简体   繁体   中英

How to embed .png into HTML email?

I'm currently using the following code to send an email (which contains a report) to users 3 times per day. I'd like to add in a graph to this email but can't seem to figure out how.

def HTML_Email(subject, to, html, files, filename):
    import smtplib  
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText                    
    from email.mime.application import MIMEApplication
    from os.path import basename
    import email
    import email.mime.application

    # Create message container - the correct MIME type is 
multipart/alternative.
    msg = MIMEMultipart('mixed')
    msg['Subject'] = subject
    msg['From'] = "ChicagoGISScripts@mobilitie.com"
    msg['To'] = ", ".join(to)

    # Record the MIME types of both parts - text/plain and text/html
    part2 = MIMEText(html, 'html')

    # create PDF attachment
    fp=open(files,'rb')
    att = email.mime.application.MIMEApplication(fp.read(),_subtype="xlsx")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)

# Attach parts into message container.
msg.attach(att)
msg.attach(part2)

# Send the message via local SMTP server.
user = 'ausername'
pwd = 'apassword'
s = smtplib.SMTP('smtp.office365.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(user,pwd)
s.sendmail(msg['From'], to, msg.as_string())
s.quit()

Typically I'll use something like this to go along with it, but I'm trying to include a .png that's stored locally on my computer. is not working to embed an image into the body of the email, what am I missing here?

html = """\
<html>
  <head></head>
  <body>
    <p><font face ="Gotham, monospace">Some HTML,<br><br>
       <img src="C:\\Users\\Me\\Desktop\\graphs.png"></img></font>
    </p>
  </body>
</html>
"""

Because you aren't hosting the image on a server, you won't be able to embed it in an email using a normal link. Try encoding the .png file into a data uri and setting that as the src

EDIT

Look at this other answer to see how to do this in python

EDIT 2

The resulting html should look like this

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

Exactly what RemedialBear said. You have to host the email on a server and have an absolute src in your email body.

Instead of:

<img src="C:\\Users\\Me\\Desktop\\graphs.png">

You need:

<img src="http://www.somedomain.com/images/graphs.png" alt="Name' />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM