[英]Send email with a table in the body without attachment
I am trying to send an email without attachement from a csv file. 我正在尝试从csv文件发送不带附件的电子邮件。 This csv file is a 3*9 cells +1 header row. 此csv文件是3 * 9单元+1标题行。
I want to send in this format in a nice format. 我想以一种很好的格式发送此格式。
This is my code: 这是我的代码:
me = 'email'
password = 'password'
server = 'smtp.gmail.com:587'
you = 'email'
text = """
Hello, Friend.
Here is your data:
{0}
Regards,
Me"""
html = """
<html><body><p>Hello, Friend.</p>
<p>Here is your data:</p>
{0}
<p>Regards,</p>
<p>Me</p>
</body></html>
"""
with open('test.csv','r') as fin:
reader=csv.reader(fin, delimiter=',')
all_text = str()
for row in reader:
temp=list(row)
all_text+= '\n'.join(row)
text = text.format(all_text, tablefmt="grid")
html = html.format(all_text, tablefmt="html")
message = MIMEMultipart(
"alternative", None, [MIMEText(text), MIMEText(html,'html')])
message['Subject'] = "Your data"
message['From'] = me
message['To'] = you
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(me, password)
server.sendmail(me, you, message.as_string())
server.quit()
It is working, but in the email there isn't any seperator, there isn't any cells, it looks very bad and unreadable. 它正在运行,但是电子邮件中没有任何分隔符,没有任何单元格,它看起来非常糟糕并且无法读取。
How can i fix the format? 如何修复格式?
Question from a csv file. 问题从一个CSV文件。 - with a table in the body - in a nice format -在身体上放一张桌子-格式不错
Example using pandas
to get both text
and html
table. 使用pandas
同时获取text
和html
表的示例。
CSV
Data CSV
数据
CSV = """Ville,Aire_urbaine,Pôle_urbain,Commune Paris,12.568.755,10.733.971,2.190.327 Lyon,2.310.850,1.651.365,515.695 Saint-Étienne,519.834,374.175,171.924 """
Read CSV
Data to pd.Dataframe
将CSV
数据读取到pd.Dataframe
df = pd.read_csv(io.StringIO(CSV), sep=',')
Format txt
格式txt
text = str(df) #text = df.to_string(index=False)
Output : 输出 :
Ville Aire_urbaine Pôle_urbain Commune 0 Paris 12.568.755 10.733.971 2.190.327 1 Lyon 2.310.850 1.651.365 515.695 2 Saint-Étienne 519.834 374.175 171.924
Format html
格式化html
html = df.to_html()
Output : 输出 :
<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>Ville</th> <th>Aire_urbaine</th> <th>Pôle_urbain</th> <th>Commune</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>Paris</td> <td>12.568.755</td> <td>10.733.971</td> <td>2.190.327</td> </tr> ... (omitted for brevity) </tbody> </table>
Tested with Python: 3.4.2 使用Python测试:3.4.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.