使用smptlib发送的电子邮件中缺少主题行

时间:2018-12-27 19:49:28

标签: python smtplib

我正在尝试使用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()

1 个答案:

答案 0 :(得分:0)

您的设置

msg['From'] = sender
msg['To'] = ", ".join(recipients)
msg['Subject'] = subject

将在您这样做后立即覆盖

msg = MIMEMultipart("alternative", None, [MIMEText(text), MIMEText(html,'html')])

稍后。

只需切换顺序并删除第一个msg = MIMEMultipart()