python - 将 html 附加到电子邮件时,“NoneType”对象没有属性“编码”错误
问题描述
我正在尝试使用 python 脚本将 html 附加到电子邮件中。我已经能够成功发送它们,但是希望有更多有组织的代码。我创建了一个函数,其中包含 HTML 作为字符串。但是,当我将其附加到电子邮件时似乎存在编码问题。我需要帮助来确定我需要在哪里设置编码。
我阅读了一些关于同样错误消息的其他帖子,他们似乎都将这行代码添加到他们的字符串中。
encode('utf8')
因此,我尝试将其附加到我认为需要去的地方,但未能取得任何成功。
这就是我所拥有的
def EmailTemplate():
test = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
def SendEmail(me, you):
# me == my email address
# you == recipient's email address
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "You've gone over your credit limit"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = ''
html = EmailTemplate()
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
当我将 HTML 作为字符串时,此代码有效。但是我现在添加了一个函数来尝试做同样的事情。
例如,这就是我以前和工作过的
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
所以我尝试用以下方法复制它。
html = EmailTemplate()
那么函数是
def EmailTemplate():
test = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
我希望电子邮件能正常发送,因为功能是一样的。但是我得到这个错误消息。
File "H:\Files\Projects\Python\Test\Htmlemail.py", line 34, in SendEmail
part2 = MIMEText(html, 'html')
File "C:\Users\vanle\AppData\Local\Programs\Python\Python37-32\lib\email\mime\text.py", line 34, in __init__
_text.encode('us-ascii')
AttributeError: 'NoneType' object has no attribute 'encode'
所以我尝试将编码添加到以下代码行
part2 = MIMEText(html.encode('utf8'), 'html')
但是我仍然收到此错误消息
File "H:\Files\Projects\Python\Test\Htmlemail.py", line 34, in SendEmail
part2 = MIMEText(html.encode('utf8'), 'html')
AttributeError: 'NoneType' object has no attribute 'encode'
解决方案
您的EmailTemplate
函数没有 return 语句,因此分配None
给您的 variable html
。添加return test
到EmailTemplate
定义的末尾应该可以解决这个问题。
def EmailTemplate():
test = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
return test
推荐阅读
- swift - 使用可编码的 Swift JSON 解码找到了一个字符串/数据
- php - 如何将 API 响应分成 2 个数组?
- python - 对不同视图的 Python Django POST 请求
- blockchain - 我可以在以太坊上存储像 excel 文件这样的数据吗?
- javascript - 使用按钮(也是图像)更改图像 - Javascript
- air - 在 AIR 的工作目录中运行可执行文件
- sql - 如何在 SQL Server 上将行作为标题
- java - 将项目上的鼠标点击存储到数组中
- postgresql - Psql Docker:无法连接到服务器:没有这样的文件或目录
- elasticsearch - Elasticsearch Painless:使用三个引号时出错:意外字符('\"'(代码 34))