【发布时间】:2019-05-25 18:50:03
【问题描述】:
我正在尝试使用 python 的 smptlib 发送一封电子邮件,除了主题键没有附加外,它似乎工作正常。 (图片[1]:https://i.stack.imgur.com/XkpLh.png)
我查看了其他解决方案,但没有一个适合我。他们主要以标题的形式解决基于文本的添加,但我的代码涉及将数据帧作为表格发送,当我尝试这些解决方案时会搞砸。
我看过的帖子:
Python: "subject" not shown when sending email using smtplib module
Subject line not coming in the smtp mail sent from python
Python smtplib sendmail() not working with subject / body
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from tabulate import tabulate
sender = 'email@email.com'
recipients = 'email@email.com'
subject = "Test Email 1234"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = ", ".join(recipients)
msg['Subject'] = subject
# Create the body of the message (a plain-text and an HTML version).
text = """
text
{table}
text
"""
html = """
<html>
<head>
<style>
table, th, td {{ border: 1px solid black; border-collapse: collapse; text-align: center;}}
th, td {{ padding: 8px; }}
</style>
</head>
<body><p>text </p>
<br><br><br>
{table}
<br><br><br>
<p>Regards,</p>
<p>abc</p>
</body></html>
"""
col_list = list(df.columns.values)
data = df
# above line took every col inside csv as list
text = text.format(table=tabulate(data, headers=col_list, tablefmt="grid"))
html = html.format(table=tabulate(data, headers=col_list, tablefmt="html"))
msg = MIMEMultipart("alternative", None, [MIMEText(text), MIMEText(html,'html')])
# Send the message via local SMTP server.
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("email@gmail.com", "pw")
server.sendmail(sender,recipients, msg.as_string())
server.quit()
【问题讨论】: