首页 > 解决方案 > 将 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'

标签: pythonhtmlemailencodingsmtp

解决方案


您的EmailTemplate函数没有 return 语句,因此分配None给您的 variable html。添加return testEmailTemplate定义的末尾应该可以解决这个问题。

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

推荐阅读