【问题标题】:Python Email in HTML format mimelibHTML 格式的 Python 电子邮件 mimelib
【发布时间】:2016-02-11 04:38:04
【问题描述】:

我正在尝试将在 Pandas Python 中创建的两个数据帧作为 html 格式发送到从 python 脚本发送的电子邮件中。

我想写一个文本和表格,并为另外两个数据框重复此操作,但脚本无法附加多个 html 块。 代码如下:

import numpy as np
import pandas as pd
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

sender = "blabla@gmail.com"
recipients = ['albalb@gmail.com']
msg = MIMEMultipart('alternative')
msg['Subject'] = "This a reminder call " + time.strftime("%c")
msg['From'] = sender
msg['To'] = ", ".join(recipients)

text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
html = df[['SYMBOL','ARBITRAGE BASIS %']].to_html()

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

username = 'blabla@gmail.com'
password = 'blahblah'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(sender, recipients, msg.as_string())
server.quit()        
print("Success")

我收到一封电子邮件,其中只有最后一部分作为电子邮件正文中的格式化 html 表格。第 1 部分文本未出现。怎么了?

【问题讨论】:

    标签: python email pandas mime


    【解决方案1】:

    使用yagmail(完全公开:我是维护者/开发者):

    import time
    import yagmail
    yag = yagmail.SMTP(username, password)
    
    text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
    html = df[['SYMBOL','ARBITRAGE BASIS %']].to_html()
    
    yag.send('albalb@gmail.com', "This a reminder call " + time.strftime("%c"), [text,html])
    

    yagmail 的存在使我们能够非常轻松地使用附件、图像和 html 等方式发送电子邮件。

    开始使用安装它

    pip install yagmail
    

    【讨论】:

      【解决方案2】:

      问题是您将这些部分标记为multipart/alternative——这意味着“我有多个渲染中的信息;选择您喜欢的那个”并且您的电子邮件客户端显然已设置为选择 HTML 版本.这两个部分实际上都在那里,但是您已将它们标记为其中之一/或显然您想要两者。

      传统的快速解决方法是切换到multipart/related,但实际上,简单地说内容在其他地方的文本部分的目的是什么?

      如果您希望 HTML 作为附件,也可以为 HTML 部分设置Content-Disposition: attachment(并提供文件名)。

      【讨论】:

      • Test Written Text Written
        这是我需要的电子邮件格式
      • 这是后续问题、新问题、对我的回答的评论,还是只是一般评论?此答案是否有助于您实现目标?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多