Send table as email body (not attachment) in Python

My input file is a CSV file, and by running some python script that consists of the python Tabulate module, I created a table that looks like this:

tabulate_output or

| Attenuation | Avg Ping RTT in ms | TCP UP | |---------------:|---------------------:|---------:| | 60 | 2.31 | 106.143 | | 70 | 2.315 | 103.624 | 

I want to send this table to the body of the letter and not as an attachment using python.

I created the sendMail function and I will wait for the table to be sent to mail_body. sendMail([to_addr], from_addr, mail_subject, mail_body, [file_name])

+5
source share
1 answer

This code sends the message in typical plain text plus html multipart / alternative format. If your correspondent reads this in an email reader that supports html, he sees an HTML table. If he reads this text application, he will see the plain text version.

In any case, he will see the data included in the message body, and not as an attachment.

 import csv from tabulate import tabulate from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib me = ' xxx@gmail.com ' password = 'yyyzzz!!2' server = 'smtp.gmail.com:587' you = ' qqq@gmail.com ' text = """ Hello, Friend. Here is your data: {table} Regards, Me""" html = """ <html><body><p>Hello, Friend.</p> <p>Here is your data:</p> {table} <p>Regards,</p> <p>Me</p> </body></html> """ with open('input.csv') as input_file: reader = csv.reader(input_file) data = list(reader) text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid")) html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html")) message = MIMEMultipart( "alternative", None, [MIMEText(text), MIMEText(html,'html')]) message['Subject'] = "Your data" message['From'] = me message['To'] = you server = smtplib.SMTP(server) server.ehlo() server.starttls() server.login(me, password) server.sendmail(me, you, message.as_string()) server.quit() 
+8
source

All Articles