Hello @Srinivasulu, Pavan Kumar
To include an image directly in the email body rather than as an attachment when using Azure Communication Services Email, you'll need to embed the image data directly into the HTML using base64 encoding.
Here's how you can modify your approach:
- First, convert your local image to a base64-encoded string.
- Then, embed this base64 string directly in your HTML.
- Finally, use this HTML as the email body when sending via Azure Communication Services Email.
Here's a step-by-step guide:
- Convert the image to base64:
import base64
def image_to_base64(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
# Convert your image
img_path = "path/to/your/img1.jpeg"
base64_image = image_to_base64(img_path)
- Modify your HTML to use the base64-encoded image:
html_content = f"""
<!DOCTYPE html>
<html>
<h1>Test Image</h1>
<img src="data:image/jpeg;base64,{base64_image}" alt="test image" width="400" height="400">
<br>
<p>This is the test email</p>
</html>
"""
- Use this HTML content when sending the email via Azure Communication Services Email:
from azure.communication.email import EmailClient
# Your connection string
connection_string = "your_connection_string_here"
# Create the EmailClient
email_client = EmailClient.from_connection_string(connection_string)
# Prepare the email
sender = "your_verified_sender@domain.com"
recipient = "recipient@example.com"
subject = "Test Email with Embedded Image"
# Send the email
poller = email_client.begin_send(
sender=sender,
recipients=[recipient],
subject=subject,
html_content=html_content
)
result = poller.result()
This approach embeds the image directly in the HTML, which means it will appear in the email body rather than as an attachment. The image is included as a Data URL, which most modern email clients support.
A few things to note:
The size of your email will increase significantly with embedded images, which might affect delivery speed or trigger spam filters if too large. Some email clients might block embedded images for security reasons, requiring the recipient to explicitly allow them. Make sure your image isn't too large, as there are typically limits on email size.
Hope that helps.
-Grace