Python Forum
How to horizontally align and display images side-by-side in an email using Python?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to horizontally align and display images side-by-side in an email using Python?
#1
How can I horizontally align and display two images side-by-side using Python and HTML in an email? I've tried adding the images using HTML code, but they're currently being displayed vertically instead of horizontally. I'm not sure what I'm doing wrong, and I've already tried a few different approaches, but none of them seem to be working. Can someone help me modify my code to display the images responsively, side by side? It seems that changes need to be made to the current below HTML code. Full code also below.

html_text = body + '<html><body><br>'
    for i, image in enumerate(images):
        html_text = body + '<html><body><br><table border="0" cellspacing="0" cellpadding="0">'
        number_of_columns = 2 # set the number of columns here
        number_of_rows = (len(images) + number_of_columns - 1) // number_of_columns
        for row in range(number_of_rows):
            html_text += "<tr>"
            for col in range(number_of_columns):
                i = row * number_of_columns + col
                if i >= len(images):
                    break
                base = os.path.basename(images[i])
                image_without_extension = os.path.splitext(base)[0]
                html_text += "<td style='vertical-align: top;'>" + image_without_extension + ":<br><img src='cid:image{}' width='100' height='100'></td>".format(i)
                html_text += "</tr>"
        html_text += """</table><br><br>
                    Best,
                    <br>
                    XYZ
                    <br>
                    Note: XYZ</body></html>"""
    text = MIMEText(html_text, 'html')
    msg.attach(text)
Here is the full python code:
import os
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import smtplib
from pretty_html_table import build_table
from mimetypes import guess_type
import os
from email.message import EmailMessage
from smtplib import SMTP_SSL
import json
import argparse
import time
import pyodbc
import pandas as pd
import warnings
warnings.filterwarnings("ignore")

def send_email_with_images(images):
    # Define the email details
    to = '[email protected]'
    sender = '[email protected]'
    subject = 'Example Email with Multiple Inline Images'

    # Create the multipart message
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = to
    msg['Subject'] = subject
    
    df = pd.read_csv('path/to/csv/file1.csv')
    df2 = pd.read_csv('path/to/csv/file2.csv')
    df3 = pd.read_csv('path/to/csv/file3.csv')

    # Create the HTML text
    name = "All"
    body = """
            <html>
            <head>
            </head>

            <body>
            Hi {3},

            <br><br>

            Please find below the report

            <br><br>

                    File1:
                    {0}
                    <br>
                    File2:
                    {1}
                    <br>
                    File3:
                    {2} 
                    
            <br><br>
            """.format(build_table(df, "blue_light", width="auto", font_family="Open Sans", font_size="13px", text_align="justify",), build_table(df2, "blue_light", width="auto", font_family="Open Sans", font_size="13px", text_align="justify",), build_table(df3, "blue_light", width="auto", font_family="Open Sans", font_size="13px", text_align="justify",), name)
    html_text = body + '<html><body><br>'
    for i, image in enumerate(images):
        html_text = body + '<html><body><br><table border="0" cellspacing="0" cellpadding="0">'
        number_of_columns = 2 # set the number of columns here
        number_of_rows = (len(images) + number_of_columns - 1) // number_of_columns
        for row in range(number_of_rows):
            html_text += "<tr>"
            for col in range(number_of_columns):
                i = row * number_of_columns + col
                if i >= len(images):
                    break
                base = os.path.basename(images[i])
                image_without_extension = os.path.splitext(base)[0]
                html_text += "<td style='vertical-align: top;'>" + image_without_extension + ":<br><img src='cid:image{}' width='100' height='100'></td>".format(i)
                html_text += "</tr>"
        html_text += """</table><br><br>
                    Best,
                    <br>
                    XYZ
                    <br>
                    Note: XYZ</body></html>"""
    text = MIMEText(html_text, 'html')
    msg.attach(text)
    
     # Add each image to the message
    for i, image in enumerate(images):
        with open(image, 'rb') as f:
            img_data = f.read()
        encoded_data = base64.b64encode(img_data).decode()
        mime_image = MIMEImage(img_data)
        mime_image.add_header('Content-ID', '<image{}>'.format(i))
        msg.attach(mime_image)

    # Send the email
    smtp = smtplib.SMTP('smtp.gmail.com', 587)
    smtp.starttls()
    smtp.login(sender, 'XYZ')
    smtp.sendmail(sender, [to], msg.as_string())
    smtp.quit()

# Example usage
send_email_with_images([r'FILE1.jpg', r'FILE2.jpg'])
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to display <IPython.core.display.HTML object>? pythopen 3 46,003 May-06-2023, 08:14 AM
Last Post: pramod08728
  How to auto align x-axis label SamLiu 2 881 Jan-27-2023, 11:10 PM
Last Post: SamLiu
  PyQT5 - align left frohr 7 4,001 May-07-2022, 09:56 PM
Last Post: deanhystad
  How can I display dictionary in a gui window in Python? C0D3R 2 1,746 Apr-07-2022, 07:33 PM
Last Post: C0D3R
  Get the Client-Side TLS ? JohnnyCoffee 1 1,359 Nov-30-2021, 10:49 PM
Last Post: Larz60+
  How can I get Python Bulk Email Verification Script With API? zainalee 1 2,496 Jun-06-2021, 09:19 AM
Last Post: snippsat
  how to read multispectral images on python noorasim 0 1,789 Feb-28-2021, 03:54 PM
Last Post: noorasim
  Need Outlook send email code using python srikanthpython 3 8,272 Feb-28-2021, 01:53 PM
Last Post: asyswow64
  4D array with only elements on one side of the diagonal schniefen 0 1,695 Dec-24-2020, 11:32 AM
Last Post: schniefen
Video Python Bulk Email Verification Script With API Aj1128 0 2,629 Nov-28-2020, 11:38 AM
Last Post: Aj1128

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020