Mã này gửi thông báo bằng văn bản thuần túy điển hình cộng với định dạng nhiều phần/thay thế html. Nếu phóng viên của bạn đọc điều này trong trình đọc thư nhận biết html, anh ta sẽ thấy bảng HTML. Nếu anh ta đọc nó đọc văn bản thuần, anh ta sẽ thấy phiên bản văn bản thuần túy.
Trong cả hai trường hợp, anh ta sẽ thấy dữ liệu được bao gồm trong nội dung thư chứ không phải dưới dạng tệp đính kèm.
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()
Nguồn
2016-07-08 22:30:59
Bạn có thể yêu cầu người nhận xem thư có phông chữ cố định chiều rộng và chỉ cần đặt bảng trong nội dung email. –
Tại sao không gửi nó dưới dạng bảng html? – Arnial
Bạn sẽ cần phải xây dựng chuỗi HTML và gửi nó qua với tiêu đề Loại nội dung thích hợp. [Ví dụ tại đây] (https://github.com/supersaiyanmode/gapi/blob/master/GApi4Term/commands/email.py#L8). – SuperSaiyan