How to add image with mail body
To add an image to 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="image.jpg" alt="Image description">
</body>
</html>
Replace image.jpg
with the actual file name and path of the image you want to add.
Method 2: Using a MIME attachment
You can attach the image as a MIME attachment to the email. 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_data = open('image.jpg', 'rb').read()
image = MIMEImage(image_data, name='image.jpg')
msg.attach(image)
server = smtplib.SMTP('smtp.example.com')
server.sendmail('[email protected]', '[email protected]', msg.as_string())
server.quit()
Replace image.jpg
with the actual file name and path of the image you want to add.
Method 3: Using a third-party library
You can use a third-party library such as email
or yagmail
to send an email with an image attachment. Here's an example using yagmail
:
import yagmail
yag = yagmail.SMTP('[email protected]', 'your_password')
subject = 'Test Email with Image'
body = 'This is a test email with an image attachment.'
image_path = 'image.jpg'
yag.send('[email protected]', subject, body, images=image_path)
Replace image.jpg
with the actual file name and path of the image you want to add.
Method 4: Using a cloud-based service
You can use a cloud-based service such as Amazon S3 or Google Cloud Storage to host your image and then link to it in your email. Here's an example:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['Subject'] = 'Test Email with Image'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
body = 'This is a test email with an image attachment.'
image_url = 'https://example.com/image.jpg'
msg.attach(MIMEText(body, 'plain'))
msg.attach(MIMEText('<img src="' + image_url + '">', 'html'))
server = smtplib.SMTP('smtp.example.com')
server.sendmail('[email protected]', '[email protected]', msg.as_string())
server.quit()
Replace image.jpg
with the actual file name and path of the image you want to add.
Note: Make sure to replace the placeholders ([email protected]
, [email protected]
, image.jpg
, etc.) with your actual email address, recipient's email address, and image file name/path.