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 #)
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With