将html附加到电子邮件时,“ NoneType”对象没有属性“ encode”错误

时间:2019-10-18 19:06:24

标签: python html email encoding smtp

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

1 个答案:

答案 0 :(得分:1)

您的EmailTemplate函数没有return语句,因此将None分配给变量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