Python函数中的HTML代码不起作用

时间:2019-11-28 13:46:50

标签: python html email formatting

我已经写了几行代码来使用smtplib模块发送电子邮件。 如果我按原样运行脚本:

import smtplib

message = """From: Sender <sender@randomemail.com>
To: Receiver <receive@randomemail.com>
Content-type: text/html
Subject: It works!
<b>It works!</b>\n
<br/>
<br/>
Do not reply to this email or god will strike you down.
"""

server = smtplib.SMTP('mysmtpserver')
sender = 'sender'
receiver = 'receive'

server.set_debuglevel(True)

server.sendmail(sender, receiver, message)

它按预期执行。而且我在收到的电子邮件中确实有HTML格式。

但是,如果我将代码作为函数与其他函数一起放在“更大”文件中:

def emailer():
    import smtplib

    message = """From: Sender <sender@randomemail.com>
    To: Receiver <receive@randomemail.com>
    Content-type: text/html
    Subject: It works!
    <b>It works!</b>\n
    <br/>
    <br/>
    Do not reply to this email or god will strike you down.
    """

    server = smtplib.SMTP('mysmtpserver')
    sender = 'sender'
    receiver = 'receive'

    server.set_debuglevel(True)

    server.sendmail(sender, receiver, message)

然后调用函数:

emailer()

我收到的电子邮件没有HTML格式,并且完全弄乱了主题和正文,然后被我的电子邮件提供商过滤为垃圾邮件。

我确实需要一些有关如何解决该问题的解释,并且还建议我是否可以以某种方式改进自己创建的内容。

谢谢

1 个答案:

答案 0 :(得分:1)

您的第二个版本在消息字符串(每行开头的空格)内有很多空白。

第一版:

From: Sender <sender@randomemail.com>
To: Receiver <receive@randomemail.com>
Content-type: text/html
Subject: It works!
<b>It works!</b>\n
<br/>
<br/>
Do not reply to this email or god will strike you down.

第二个版本:

From: Sender <sender@randomemail.com>
    To: Receiver <receive@randomemail.com>
    Content-type: text/html
    Subject: It works!
    <b>It works!</b>\n
    <br/>
    <br/>
    Do not reply to this email or god will strike you down. 

如果两封电子邮件的内容之间存在差异,则可能是这样。