How to embed image using cid in mail body
Embedding an image using a CID (Content ID) in the body of an email involves several steps:
Step 1: Convert the image to a MIME-encoded attachment
You need to convert the image file to a MIME-encoded attachment. You can use a library or tool to do this. For example, in Python, you can use the mimetypes
and email.mime
modules:
import mimetypes
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
image_file = open('image.jpg', 'rb')
mimetype, _ = mimetypes.guess_type(image_file.name)
if mimetype is None:
mimetype = 'image/jpeg'
msg = MIMEMultipart()
msg['Content-Type'] = f'multipart/related; boundary="{mimetype}"'
msg['Content-Disposition'] = 'inline; filename="image.jpg"'
image = MIMEImage(image_file.read(), mimetype=mimetype)
msg.attach(image)
Step 2: Generate a CID
Generate a unique CID for the image. You can use a random number generator or a UUID library:
import uuid
cid = f'<{uuid.uuid4().hex}>'
Step 3: Add the CID to the image attachment
Add the CID to the image attachment:
image.add_header('Content-ID', cid)
Step 4: Add the image attachment to the email body
Add the image attachment to the email body:
msg.attach(image)
Step 5: Set the Content-Type
header
Set the Content-Type
header of the email to multipart/related
:
msg['Content-Type'] = 'multipart/related; boundary="----BOUNDARY----"'
Step 6: Set the boundary
parameter
Set the boundary
parameter to a unique string:
boundary = '----BOUNDARY----'
msg['Content-Type'] = f'multipart/related; boundary="{boundary}"'
Step 7: Send the email
Send the email using your preferred email library or service.
Here's the complete code example:
import mimetypes
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import uuid
image_file = open('image.jpg', 'rb')
mimetype, _ = mimetypes.guess_type(image_file.name)
if mimetype is None:
mimetype = 'image/jpeg'
msg = MIMEMultipart()
msg['Content-Type'] = f'multipart/related; boundary="{mimetype}"'
msg['Content-Disposition'] = 'inline; filename="image.jpg"'
cid = f'<{uuid.uuid4().hex}>'
image = MIMEImage(image_file.read(), mimetype=mimetype)
image.add_header('Content-ID', cid)
msg.attach(image)
msg['Content-Type'] = 'multipart/related; boundary="----BOUNDARY----"'
boundary = '----BOUNDARY----'
msg['Content-Type'] = f'multipart/related; boundary="{boundary}"'
# Send the email using your preferred email library or service
When the email is received, the image will be embedded in the body using the CID. The recipient's email client will display the image inline.