以下是一个示例代码,演示了如何遍历一个表格,并将结果传递给一个用于发送电子邮件的HTML表格。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(html_content):
# 设置发件人、收件人、主题等信息
sender = 'your_email@example.com'
recipient = 'recipient_email@example.com'
subject = 'Table Data'
password = 'your_email_password'
# 创建HTML邮件内容
message = MIMEMultipart()
message['From'] = sender
message['To'] = recipient
message['Subject'] = subject
# 将表格数据作为HTML内容添加到邮件中
html_body = """
Header 1
Header 2
{table_content}
""".format(table_content=html_content)
message.attach(MIMEText(html_body, 'html'))
# 发送邮件
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login(sender, password)
server.sendmail(sender, recipient, message.as_string())
# 示例表格数据
table_data = [
['Data 1', 'Data 2'],
['Data 3', 'Data 4'],
['Data 5', 'Data 6']
]
# 构建HTML表格内容
table_content = ''
for row in table_data:
table_content += ''
for cell in row:
table_content += '{} '.format(cell)
table_content += ' '
# 发送邮件
send_email(table_content)
以上代码示例中,首先我们使用smtplib库和email库来发送电子邮件。在send_email函数中,我们设置了发件人、收件人、主题等信息,并创建一个MIMEMultipart对象来存储邮件内容。
然后,我们使用一个HTML模板来创建HTML表格内容。在模板中,我们使用占位符{table_content}来动态插入表格数据。接下来,我们使用MIMEText将HTML内容添加到邮件中。
在示例表格数据中,我们使用一个二维列表来表示表格数据。然后,我们遍历表格数据,将每个单元格的内容添加到HTML表格的对应位置。
最后,我们调用send_email函数,将HTML表格内容作为参数传递进去,发送电子邮件。