如何使用Python和HTML在电子邮件中水平对齐并并排显示图像?

ioekq8ef  于 2023-02-26  发布在  Python
关注(0)|答案(3)|浏览(159)

如何在电子邮件中使用Python和HTML水平对齐并并排显示两个图像?我尝试过使用HTML代码添加图像,但它们目前是垂直显示而不是水平显示。我不确定我做错了什么,我已经尝试了几种不同的方法,但似乎都不起作用。有人能帮我修改代码以响应地显示图像吗?并排?似乎需要对下面的HTML代码进行更改。完整的代码也在下面。

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)
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 = 'receiver@example.com'
    sender = 'sender@example.com'
    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'])
dffbzjpn

dffbzjpn1#

循环的输出显示为

<tr>
  <td> (image1) </td>
</tr>
<tr>
  <td> (image2) </td>
</tr>

您希望图像作为同一行中的相邻单元格,而不是将图像放置在单独的行中:

<tr>
  <td> (image1) </td><td> (image2) </td>
</tr>

您仍然需要考虑电子邮件的宽度(通常由具有固定宽度的父表设置,并且仍然有很多东西可以打乱您的布局(图像尺寸、table/td元素属性),但这将使您走上正确的轨道:)

mspsb9vt

mspsb9vt2#

看起来你需要shift + tab @

html_text += "</tr>"

因为这会打断for循环中的行

0md85ypi

0md85ypi3#

您可以将每个图像放入一个div元素中,并将两个div元素放入一个父div中:

def send_email_with_images(paths_list):
    #do stuff
    html_text = '<div>' \
        f'<div style="width:50%; float:left;"><img style="width:100%;" src={paths_list[0]}></div>' \
        f'<div style="width:50%; float:left;;"><img style="width:100%;" src={paths_list[1]}></div>' \
        '</div>' 

    # do stuff

相关问题