python-3.x - 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 结束
解决方案
您得到的错误是因为您没有将值分配给电子邮件字典,如文档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'
推荐阅读
- c# - Labell.Text 只会更新一次
- python - 熊猫:Any() All() with if/else
- python - 如何在python中访问派生属性类中的方法和属性
- c++ - 如何判断函数参数是否可以安全删除
- amazon-web-services - Cloudformation 参数 ViewerProtocolPolicy:“重定向到 https”正在失效
- git - Notepad++ 找不到 COMMIT_EDITMSG 文件
- sql - 需要拆分逗号分隔的字符串并循环它
- javascript - 按特定属性的最大值过滤数组元素
- excel - 在 VBA 中的 2 个工作簿中基于多个条件删除行
- android - LiveData 未设置,观察者从未被调用