Add image in mail body
To add an image in the body of an email, you can use the following methods:
Method 1: Using HTML
You can use HTML to embed an image in the email body. Here's an example:
<html>
<body>
<img src="cid:image1" alt="Image 1">
</body>
</html>
In this example, cid:image1
is a content ID that references the image file. You'll need to attach the image file to the email and set its content ID to image1
.
Method 2: Using a MIME attachment
You can also attach the image file to the email as a MIME attachment. Here's an example:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
msg = MIMEMultipart()
msg['Subject'] = 'Test Email with Image'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
image = MIMEImage(open('image.jpg', 'rb').read())
image.add_header('Content-Disposition', 'attachment', filename='image.jpg')
msg.attach(image)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('[email protected]', 'your_password')
server.sendmail('[email protected]', '[email protected]', msg.as_string())
server.quit()
In this example, we create a MIMEImage
object and attach it to the email message using the attach()
method. We also set the Content-Disposition
header to attachment
to indicate that the image should be downloaded as a file.
Method 3: Using a third-party library
There are several third-party libraries available that can help you add images to email bodies. For example, you can use the yagmail
library in Python:
import yagmail
yag = yagmail.SMTP('[email protected]', 'your_password')
yag.send('[email protected]', 'Test Email with Image', ['image.jpg'])
In this example, we create a yagmail
object and use its send()
method to send an email with an attached image.
Note: When sending emails with images, make sure to check the recipient's email client settings to ensure that they can receive and display images. Some email clients may block images by default or require the recipient to explicitly allow them.