Reputation: 151
I am trying to send an email without attachement from a csv file. This csv file is a 3*9 cells +1 header row.
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?
Upvotes: 0
Views: 607
Reputation: 15523
Question from a csv file. - with a table in the body - in a nice format
Example using pandas
to get both text
and html
table.
CSV
Data
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
df = pd.read_csv(io.StringIO(CSV), sep=',')
Format 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 = 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
Upvotes: 1