Python格式的电子邮件mimelib

时间:2015-11-10 10:17:32

标签: python email pandas mime

我正在尝试将从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部分文本没有出现。怎么了?

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分: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
相关问题