1

I use python for sending Email.I need to insert picture to body e-mail like this :

I need like this:

But my output not show image like this :

enter image description here

I try many solution for fix it but it ineffectively. This's my code is below :

import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
import pandas as pd
import win32com.client as win32
import openpyxl
import sys
from PIL import ImageGrab
from pathlib import Path
df = pd.read_excel("xxxxx", sheet_name = "sample",nrows = 2, usecols = "A:W")
df1 = pd.read_excel("xxxx", sheet_name = "sample")
excel_path = ("sample")
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = False
excel.DisplayAlerts = False
wb = excel.Workbooks.Open(excel_path)
ws = wb.Worksheets(1)
win32c = win32.constants
ws.Range("A1:H33").CopyPicture(Format=win32c.xlBitmap)
img = ImageGrab.grabclipboard()
image_path = str("path" + 'te.png')
img.save(image_path)
outlook = win32.gencache.EnsureDispatch('Outlook.Application')
new_mail = outlook.CreateItem(0)
user = df1.loc[34,"Unnamed: 4"]
approver = df1.loc[36,"Unnamed: 4"]
def FIN(xReceiveTO,xReceiveCC, xsubject, xBody):
  FROM = '[email protected]'
  TO = '[email protected]'
  CC = ""  
  #msg = MIMEMultipart()
  msg = MIMEText("<html><body><h1>ดำเนินการส่งให้ทีม AP แล้ว</h1>" +
                 "<p>รายละเอีดตามข้อมูลด้านล่าง" +
                 "html_pages + <br><img src=te.png>"+
                 "<a href=""mailto:[email protected]?cc=" + user + ";"+ approver + "&subject=Invoice%20ฉบับนี้ผ่านการพิจารณาอนุมัติจาก%20หัวหน้าทีมแล้ว%20รบกวนทีม%20AP%20ตรวจสอบสอบส่งต่อไปทีม%20Financial%20Planing%20and%20Analytics%20ครับ&body=ทีม%20AP%20ได้ทำการตรวจสอบแล้วมีความเห็นว่าสมควร%20Approve%20ครับ>Approve</a> "+" "+"<a href=""mailto:[email protected]?cc=" +user + ";"+ approver + "&subject=Invoice%20ฉบับนี้ไม่ผ่านการพิจารณาอนุมัติจากทีม%20AP&body=ทีม%20AP%20ได้ทำการตรวจสอบแล้วมีความเห็นว่าสมควร%20Reject%20ครับ%20>Reject</a>"
                 "</body></html>","html","utf-8""")
  #msg['Subject'] =  Header(subject, 'utf-8')
  msg['Subject'] =  "Test"
  msg['To'] = ', '.join(xReceiveTO)
  msg['CC'] = ', '.join(xReceiveCC)
  msg['FROM'] = FROM
  s = smtplib.SMTP('10.45.1.25')
  s.send_message(msg)
  s.quit()

Please tell me how to add image to my body email /.

1
  • 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.
    – JoshuaHew
    Sep 7, 2022 at 16:05

1 Answer 1

7

Main message has to be set to MIMEMultipart with 'related' subtype (first argument).

Then, the image has to be attached with content-id, as such:

msg = MIMEMultipart("related")
msg["Subject"] = subject
msg["From"] = from_addr
msf["To"] = to_addr

html_output = "your html here"

msg.attach(MIMEText(html_output, "html"))
if images:
    for image_name, image_location in images.items():
        with open(image_location, "rb") as fp:
            img = MIMEImage(fp.read())
        img.add_header("Content-ID", "<{}>".format(image_name))
        msg.attach(img)

smtplib.SMTP(host, port).sendmail(self.from_addr, to_addr, msg.as_string())

[This is part of my email wrapper, hence "images" is a dict and such.]

To refer to the image in the html, in src use cid: and the name (the same that was used to attach the pic to the email), e.g.

<img src="cid:logo"/>
5
  • 2
    Thanks! This is the only working solution I have found. I found a bit odd that you used: smtplib.SMTP(host, port).sendmail(self.from_addr, to_addr, msg.as_string()) instead of: smtplib.SMTP(host, port).send_message(msg)
    – OrizG
    Mar 26, 2021 at 16:58
  • 2
    @OrizG, I just checked docs and it seems SMTP.send_message uses Message object. I've always constructed html emails from MIME types, so any example/tutorial I found when I was learning this seemed to use SMTP.sendmail, so I just always used it. I don't even know if send_message would work with MIMEMultipart or would it need more tweaking?
    – h4z3
    Mar 26, 2021 at 19:27
  • I confirm that the send_message method accepts the MIMEMultipart object. I just finished a project that sends out over 5,000 statements each one of those tailored for every single customer. It was a great success, thanks again!
    – OrizG
    Mar 27, 2021 at 22:43
  • Im using an email client that doesn't seem to accept cid. Is this unusual? Edit: I think its actually blocking CSS. Not sure how pictures get embeded by default. May 24 at 21:22
  • @MrChadMWood Is that Thunderbird? Did you make sure to make the email as 'related' like I said at the beginning? Thunderbird is quite set on following the specs (default used for multipart is 'alternative' which is e.g. when you have both plaintext and html content; while parts that should work together are 'related'), while some other clients are more lenient.
    – h4z3
    May 25 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.