使用电子邮件中的HTML并发发送两个熊猫数据帧

时间:2019-01-03 10:38:07

标签: python html css pandas html-email

我正尝试通过电子邮件发送一些有关我的股票投资组合创建的摘要。我正在使用Python + Pandas进行计算,并使用email.mime模块通过电子邮件发送html。

我正在使用Pandas的to_html方法和email.mime模块将html包含在电子邮件中:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

import numpy as np
import pandas as pd
import pickle
from utils import mail


def send_fancy_mail(subject, text_message, html_message):

    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = 'mymail@domain.com'
    msg['To'] = settings.MAIL_RECIPIENTS

    # Record the MIME types of both parts - text/plain and text/html.
    part1 = MIMEText(text_message, 'plain')
    part2 = MIMEText(html_message, 'html')
    msg.attach(part1)
    msg.attach(part2)

    # Send the message via our own SMTP server.
    s = smtplib.SMTP_SSL(settings.SMTP_HOST)
    s.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
    s.send_message(msg)
    s.quit()

fake_or_load = 'fake'

if fake_or_load == 'fake':
    n_signals = 20
    symbols = np.round(1000*np.random.rand(n_signals)).astype(int)
    direction = ["Buy" for i in range(n_signals//2)]
    direction.extend(["Sell" for i in range(n_signals//2)])
    quantity = np.round(10000*np.random.rand(n_signals)).astype(int)

    portfolio = pd.DataFrame({'symbols': symbols, 'direction': direction, 'quantity': quantity})

elif fake_or_load == 'load':
    with open('c:\\\\temp\\signals_list', 'rb') as fp:
        signals = pickle.load(fp)

    portfolio = pd.DataFrame(signals)
    portfolio.rename(index=str, inplace=True, columns={0: "symbol", 1: "direction", 2: "quantity"})


shares_to_buy = portfolio[portfolio['direction'] == 'Buy'].copy()
shares_to_buy.sort_values(by='quantity', inplace=True, ascending=False)

shares_to_sell = portfolio[portfolio['direction'] == 'Sell'].copy()
shares_to_sell.sort_values(by='quantity', inplace=True, ascending=False)

# The basic way to convert portfolio to html:
html_to_buy = shares_to_buy.to_html(index=False, header=True, col_space=20, justify='center')
html_to_sell = shares_to_sell.to_html(index=False, header=True, col_space=20, justify='center')

mail_body = "Test Message"
css = """
.div {
    flex-direction: row;
}
"""

html_body = """
<html>
  <head>
  <style>{}</style>
  </head>
  <body>
  <div>{}</div>
  <div>{}</div>
  </body>
</html>
""".format(css, html_to_buy, html_to_sell)

mail.send_fancy_mail("Test Mail", mail_body, html_body)

我希望在电子邮件正文中并排放置两列,最好也能调节列宽。是否可以使表响应?

1 个答案:

答案 0 :(得分:1)

如果要创建两列,请用下表替换两个div。 Div的支持与所有电子邮件客户端上的表不同。

  <table style="width:100%">
    <tr>
      <td>column 1</td>
      <td>column 2</td> 
    </tr>
  </table>