首页 > 解决方案 > from_addr = email.utils.getaddresses([from_addr])[0][1] ,使用 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 结束

标签: python-3.xemailsmtplib

解决方案


您得到的错误是因为您没有将值分配给电子邮件字典,如文档NoneType中所示。string

更具体地说,在这里:

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'

推荐阅读