Gmail API发送带附件邮件触发递归错误求助
解决Gmail API发送带附件邮件时的无限循环问题
问题根源分析
代码存在两个致命错误,直接触发了递归无限循环:
- 变量冲突+递归引用:函数参数
message是字符串类型,但你在函数内部又创建了同名的EmailMessage对象,随后调用message.set_content(message)时,实际是把EmailMessage对象本身作为内容传入,形成递归引用,最终导致as_bytes()处理时陷入无限循环。 - API请求体错误:构建
create_message时,你传入了原始的message对象,而Gmail API要求的是经过base64编码后的字符串。
修复后的完整代码
from __future__ import print_function from google.oauth2.credentials import Credentials from googleapiclient.discovery import build from googleapiclient.errors import HttpError import base64 from email.message import EmailMessage SCOPES = ['https://www.googleapis.com/auth/gmail.send'] def send_email(content: str, subject: str, to_email: str, attachments: list=None): """创建并发送带附件的邮件,返回消息ID""" creds = Credentials.from_authorized_user_file('token.json', SCOPES) try: service = build('gmail', 'v1', credentials=creds) # 重命名变量,彻底避免和函数参数冲突 msg = EmailMessage() # 传入正确的字符串内容,而非EmailMessage对象本身 msg.set_content(content) if attachments: for attachment in attachments: with open(attachment, 'rb') as content_file: file_content = content_file.read() # 处理无后缀的文件,避免索引错误 file_ext = attachment.split('.')[-1] if '.' in attachment else 'octet-stream' msg.add_attachment(file_content, maintype='application', subtype=file_ext, filename=attachment) msg['To'] = to_email msg['From'] = 'gduser1@workspacesamples.dev' msg['Subject'] = subject # 编码邮件内容为API要求的格式 encoded_message = base64.urlsafe_b64encode(msg.as_bytes()).decode() # 使用编码后的字符串构建请求体 create_message = { 'raw': encoded_message } send_result = service.users().messages().send(userId="me", body=create_message).execute() print(f'Message Id: {send_result["id"]}') except HttpError as error: print(f'An error occurred: {error}') send_result = None return send_result
关键修改说明
- 重命名函数和参数:将
send_message改为send_email,原参数message改为content,彻底避免变量名冲突。 - 修正内容设置:
msg.set_content(content)传入正确的字符串邮件内容,而非对象自身。 - 优化附件后缀处理:避免无后缀文件导致的索引错误。
- 修复API请求体:
raw字段传入编码后的字符串,符合Gmail API要求。
内容的提问来源于stack exchange,提问作者Christian Trujillo
相关产品推荐
相关产品推荐

