使用SendGrid Python代码报错:找不到rfc822模块及循环导入问题
问题描述
使用SendGrid示例代码验证Token可用性时,反复出现与RFC822相关的错误,示例代码如下:
import os import sendgrid from sendgrid.helpers.mail import Mail message = Mail( from_email='someone@gmail.com', to_emails='someone@gmail.com', subject='Sending with Twilio SendGrid is Fun', html_content='<strong>and easy to do anywhere, even with Python</strong>') try: sg = sendgrid.SendGridAPIClient('some token') response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message)
收到的错误信息:
ModuleNotFoundError: No module named 'rfc822' During handling of the above exception, another exception occurred: ImportError: cannot import name 'Mail' from partially initialized module 'sendgrid.helpers.mail' (most likely due to a circular import) (/home/userrrr/.local/lib/python3.8/site-packages/sendgrid/helpers/mail/__init__.py)
已尝试使用Python3、pip3,切换SendGrid旧版本,在Windows和Ubuntu系统测试,问题仍存在。
解决思路
安装Python3.8兼容的指定版本SendGrid
rfc822是Python2专属模块,Python3中已被email模块替代,错误说明当前SendGrid版本与Python3.8不兼容。执行以下命令重装兼容版本:pip3 uninstall sendgrid pip3 install sendgrid==6.10.0清理pip缓存并重装
若多次安装不同版本导致依赖混乱,先清理缓存再重新安装:pip3 cache purge pip3 install sendgrid==6.10.0使用虚拟环境隔离依赖
避免全局环境包冲突,创建并激活虚拟环境后安装依赖:python3 -m venv sendgrid_env # Ubuntu/Debian系统激活命令 source sendgrid_env/bin/activate # Windows系统激活命令 sendgrid_env\Scripts\activate pip3 install sendgrid==6.10.0修正导入方式避免隐式依赖
替换导入语句为更明确的形式,避免循环导入问题:from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, From, To, Subject, HtmlContent message = Mail( from_email=From('someone@gmail.com'), to_emails=To('someone@gmail.com'), subject=Subject('Sending with Twilio SendGrid is Fun'), html_content=HtmlContent('<strong>and easy to do anywhere, even with Python</strong>') )排查本地文件名冲突
确保当前项目目录下没有名为sendgrid.py或mail.py的文件,这类文件会覆盖官方模块,导致导入错误。
内容的提问来源于stack exchange,提问作者Joseph Khella
相关产品推荐
相关产品推荐

