Send table as an email body (not attachment ) in Python Send table as an email body (not attachment ) in Python python python

Send table as an email body (not attachment ) in Python


This code sends the message in the typical plain text plus html multipart/alternative format. If your correspondent reads this in an html-aware mail reader, he's see the HTML table. If he reads it plain-text reader, he'll see the plain text version.

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

import csvfrom tabulate import tabulatefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport smtplibme = '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'] = memessage['To'] = youserver = smtplib.SMTP(server)server.ehlo()server.starttls()server.login(me, password)server.sendmail(me, you, message.as_string())server.quit()