How can I embed an image into an email message?

Viewed 76

and thanks in advance for helping out. I've been trying to embed an image on this specific code. I've followed some other posts related to this but the result hasn't shown the image displayed when the email is opened. It just shows it as an attachment. Any guidance will be more than helpful. Thanks again!

import email, smtplib, ssl
import os
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

#body = """                    Attached are your results! 

#Feel free to reply to this message if you have any questions.
#        We look forward to working with you soon.

#            Thank you for using Weckrogrid-20!                      """
sender_email = "WeckroGrid-20"
receiver_email = "*****@gmail.com"

# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = 'WeckroGrid-20'
#message["To"] = '*****@gmail.com'
message["Subject"] = 'Your Microgrid Plan is here!'
#message["Bcc"] = 'receiver_email'  # Recommended for mass emails

# Add body to email
#message.attach(MIMEText(body, "plain"))

filename = "dummy.pdf"  # In same directory as script

# Open PDF file in binary mode
with open(filename, "rb") as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode file in ASCII characters to send by email    
encoders.encode_base64(part)

# Add header as key/value pair to attachment part
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)
#Add attachment to message and convert message to string
message.attach(part)
text = message.as_string('')

# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login('******@gmail.com', '*******')
    server.sendmail(sender_email, receiver_email, text)
0 Answers
Related