from_addr = email.utils.getaddresses([from_addr])[0][1] ,使用 python 发送电子邮件时出错

from_addr = email.utils.getaddresses([from_addr])[0][1] , error while sending the email using python

使用 python 发送电子邮件时出现以下错误,我需要创建对象吗?

import smtplib
from email.message import EmailMessage

email = EmailMessage()
email['from']: 'xxxxx@gmail.com'
email['to']: "xxxxx@gmail.com"
email['subject']: 'Hey Buddy Python'

email.set_content("Learning python")

with smtplib.SMTP(host="smtp.gmail.com", port="587") as smtp:
    smtp.ehlo()
    smtp.starttls()
    smtp.login("xxxx@gmail.com", "xxxx")
    smtp.send_message(email)   

程序输出:

Traceback (most recent call last):
  File "C:/Users/xxxxx/Desktop/PYTHON/PyCharm/Email/SendEmail.py", line 15, in <module>
    smtp.send_message(email)
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 940, in send_message
    from_addr = email.utils.getaddresses([from_addr])[0][1]
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python38-32\lib\email\utils.py", line 112, in getaddresses
    all = COMMASPACE.join(fieldvalues)
TypeError: sequence item 0: expected str instance, NoneType found

进程已完成,退出代码为 1

您收到 NoneType 而不是 string 的错误是因为您没有将值分配给电子邮件字典,如 documentation.

中所示

更具体地说,在这里:

email['from']: 'xxxxx@gmail.com'
email['to']: "xxxxx@gmail.com"
email['subject']: 'Hey Buddy Python'

您应该使用赋值运算符 =,而不是 :

试试:

email['from'] = 'xxxxx@gmail.com'
email['to'] = "xxxxx@gmail.com"
email['subject'] ='Hey Buddy Python'