【问题标题】:Missing subject line on email sent using smptlib使用 smptlib 发送的电子邮件缺少主题行
【发布时间】: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()

【问题讨论】:

    标签: python smtplib


    【解决方案1】:

    您的设置

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

    一旦你这样做,就会被覆盖

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

    稍后。

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

    【讨论】:

    • 成功了!!感谢您提供此解决方案!没有意识到我正在这样做:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 2015-04-29
    • 2017-12-26
    • 2016-11-12
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多