該代碼以典型純文本加html多部分/替代格式發送消息。如果你的記者在一個支持html的郵件閱讀器中讀到這個,他會看到HTML表格。如果他讀它純文本閱讀器,他會看到純文本版本。
無論哪種情況,他都會看到郵件正文中包含的數據,而不是作爲附件。
import csv
from tabulate import tabulate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
me = '[email protected]'
password = 'yyyzzz!!2'
server = 'smtp.gmail.com:587'
you = '[email protected]'
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()
您可以要求收件人查看固定寬度字體的郵件,並將表格放在電子郵件正文中。 –
爲什麼不把它作爲html表發送? – Arnial
您需要構建HTML字符串,並使用適當的Content-Type標題發送它。 [一個例子](https://github.com/supersaiyanmode/gapi/blob/master/GApi4Term/commands/email.py#L8)。 – SuperSaiyan