Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed picture in email

I currently have a program that will randomly select quotes from a list and email them. I'm now trying to embed an image in the email as well. I've come across a problem where I can attach the email but my quotes no longer work. I have researched online and the solutions are not working for me. Note that I am using Python 3.2.2.

Any guidance would be appreciated.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

attachment = 'bob.jpg' 

msg = MIMEMultipart()
msg["To"] = to_addr
msg["From"] = from_addr
msg["Subject"] = subject_header

#msgText = MIMEText(<b>%s</b><br><img src="cid:bob.jpg"><br>, 'html') % body

fp = open(attachment, 'rb')
img = MIMEImage(fp.read())
fp.close()

msg.attach(img)

#email_message = '%s\n%s\n%s' % (subject_header, body, img)
email_message = '%s\n%s' % (subject_header, body)

emailRezi = smtplib.SMTP(mail_server, mail_server_port)
emailRezi.set_debuglevel(1)
emailRezi.login(mail_username, mail_password)
emailRezi.sendmail(from_addr, to_addr, email_message)
#emailRezi.sendmail(from_addr, to_addr, msg.as_string())
emailRezi.quit()

As you can tell from the code above I've tried different ways (referencing the #)

like image 819
Paul Avatar asked Oct 13 '11 14:10

Paul


People also ask

Can you embed images in an email?

There are three primary methods for embedding an image into an email: Linking the image, inline embedding, and Content-ID (CID). All three methodologies have pros and cons and require a certain level of expertise to implement, but all are valuable techniques.

What does it mean to embed an image in an email?

Embedding images in an email message involves adding the message into the text, much as they appear on a website, rather than adding them as attachments. This is a good way to ensure that clients and business partners will see the images while reading the email.


2 Answers

You are going through royal pains to construct a valid MIME message in msg, then ditching it and sending a simple string email_message instead.

You should probably begin by understanding what the proper MIME structure looks like. A multipart message by itself has no contents at all, you have to add a text part if you want a text part.

The following is an edit of your script with the missing pieces added. I have not attempted to send the resulting message. However, see below for a modernized version.

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText  # Added
from email.mime.image import MIMEImage

attachment = 'bob.jpg'

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

msgText = MIMEText('<b>%s</b><br/><img src="cid:%s"/><br/>' % (body, attachment), 'html')   
msg.attach(msgText)   # Added, and edited the previous line

with open(attachment, 'rb') as fp:
    img = MIMEImage(fp.read())
img.add_header('Content-ID', '<{}>'.format(attachment))
msg.attach(img)

print(msg.as_string()) # or go ahead and send it

(I also cleaned up the HTML slightly.)

Since Python 3.6, Python's email library has been upgraded to be more modular, logical, and orthogonal (technically since 3.3 already really, but in 3.6 the new version became the preferred one). New code should avoid the explicit creation of individual MIME parts like in the above code, and probably look more something like

from email.message import EmailMessage
from email.utils import make_msgid

attachment = 'bob.jpg'

msg = EmailMessage()
msg["To"] = to_addr
msg["From"] = from_addr
msg["Subject"] = subject

attachment_cid = make_msgid()

msg.set_content(
    '<b>%s</b><br/><img src="cid:%s"/><br/>' % (
        body, attachment_cid[1:-1]), 'html')

with open(attachment, 'rb') as fp:
    msg.add_related(
        fp.read(), 'image', 'jpeg', cid=attachment_cid)

# print(msg.as_string()), or go ahead and send

You'll notice that this is quite similar to the "asparagus" example from the email examples documentation in the Python standard library.

like image 150
tripleee Avatar answered Sep 22 '22 05:09

tripleee


I have edited for attaching the image on a message body and HTML template.

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

strFrom = '[email protected]'
strTo = '[email protected]'

# Create the root message 

msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot['Cc'] =cc
msgRoot.preamble = 'Multi-part message in MIME format.'

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('Alternative plain text message.')
msgAlternative.attach(msgText)

msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>KPI-DATA!', 'html')
msgAlternative.attach(msgText)

#Attach Image 
fp = open('test.png', 'rb') #Read image 
msgImage = MIMEImage(fp.read())
fp.close()

# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

import smtplib
smtp = smtplib.SMTP()
smtp.connect('smtp.gmail.com') #SMTp Server Details
smtp.login('exampleuser', 'examplepass') #Username and Password of Account
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
like image 21
Sachin Avatar answered Sep 20 '22 05:09

Sachin