I am testing a email notification system with python and selenium with mailgun API.
everything works well except images were not showing up in gmail, i found out that gmail have problems referencing outside images.
So i am currently attaching all the images in the email itself and sending with CID referencing so images show up in html. In my end the html shows ok with cid , but when the email is sent src of the CID is being deleted, not present anymore.
selenium code
attachlist = []
for attr in driver.find_elements_by_xpath('//table[@id="mainTable"]/tbody/tr[contains(@id, "cell_")]'):
imgN = uuid.uuid4().hex
imgattr = attr.find_element_by_xpath('.//td[4]/a[1]/img[1]')
imglink = imgattr.get_attribute('src')
r = requests.get(imglink, stream=True)
if r.status_code == 200:
with open(str(imgN)+'.jpg', 'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
attachlist.append(('attachment', open(str(imgN)+'.jpg', 'rb')))
driver.execute_script('arguments[0].setAttribute("src","cid:{}");'.format(str(imgN)+'.jpg'), imgattr)
#driver.execute_script('arguments[0].setAttribute("alt", "SpaceImage");', imgattr)
driver.execute_script('arguments[0].setAttribute("style", "display: block");', imgattr)
driver.execute_script('arguments[0].removeAttribute("load_src");', imgattr)
elem = driver.find_element_by_xpath('//table[@id="mainTable"]')
resp = elem.get_attribute('innerHTML')
resp = "<<!DOCTYPE html><html><head><title>Title of the document</title></head><body>"+str(resp)+"</body></html>"
r = requests.post(
"https://api.mailgun.net/v3/mysandbox.mailgun.org/messages",
auth=("api", "my-key"),
files=attachlist,
data={"from": "mailgun@mysandbox.mailgun.org",
"to": ["recipient1@gmail.com", "recipient@gmail.com"],
"subject": "the subject",
"text": "The text",
"html": resp}
)
here i am getting a table, changing the images src with javascript then enclosing that table in a html and sending it with all the attachments.
the images src before sending the email
<img src="cid:7545abfbeec84eff98a82a3bb79baea1.jpg" border="0" name="img_preview" width="72" style="display: block">
Here it is after i send the email, src is going away in Gmail
<img name="m_-3792568815060333898_img_preview" style="display:block" width="72" border="0">
see the attachments are there but image src is vanishing in gmail which references the CID
What is happening here ? what am i doing wrong ?
Thanks for reading, Have wonderful day :)