Image embedded in email also becomes an attachment

51 views Asked by At

A script that is correctly embedding inline images in HTML emails, is also adding the images as attachments. How can I eliminate this second copy of each image?

If any intended attachments are included, they're processing correctly. With or without attachments, all images appear in the body of the message, and then again as an attachment. Removing the section for attachments (# Attach any files) makes no difference on the images. They still get included twice.

#!/usr/bin/python3

import smtplib
from email.message import EmailMessage
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
from email.mime.audio import MIMEAudio
import mimetypes

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

msg = EmailMessage()
msg['Subject'] = 'This is a test at 1:22'
msg['From'] = strFrom 
msg['To'] = strTo 
msg.set_content('''
<!DOCTYPE html>
<html>
    <body>
                    <p><img src="cid:image1"/></p>
                    <p>Python email test</p>
                    <p><img src="cid:image2"/></p>
    </body>
</html>
''', subtype='html')

msg.make_mixed()

# Attach Any Images
images = '''/Users/my/Desktop/RKw.jpeg\n/Users/my/Desktop/logo.png'''.splitlines()
i=1
for image in images:
    # print 'Image',i,': ',image,'\n'
    fp = open(image, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    # Define the image's ID as referenced above
    msgImage.add_header('Content-ID', '<image'+str(i)+'>')
    msg.attach(msgImage)
    i+=1


# Attach any files
files = ''''''.splitlines()
for file in files:
    ctype, encoding = mimetypes.guess_type(file)
    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    with open(file, 'rb') as fp:
        msg.add_attachment(fp.read(),
                           maintype=maintype,
                           subtype=subtype,
                           filename=file.split('/')[-1].replace(' ','%20'))
                               
                                                 
with smtplib.SMTP_SSL('smtpserver.com', 465) as smtp:
    smtp.login(strFrom, strPWord) 
    smtp.send_message(msg)
1

There are 1 answers

3
Eugene Astafiev On

If you need to attach a single image and then use it in different places of the message body, you can attach it once and use CID attribute for referring to the embedded image without re-attaching the file anew. The same attached file will be used that way.