[英]how to send email with attachment through Gmail API
这可能以前被问过,但我没有看到这个具体问题,至少无法识别
I finally figured out how to send an email through the Gmail API, and now need to add attachments, so I edited the code found on Google's API guide basically just adding some arguments and adding in the "message.add_attachment()" part you see以下。 问题是当“message.to_bytes”被调用时,它开始了一些无限循环,我根本无法理解这两种方法的文献。 谁能帮我对这个 email object 进行编码,以便我可以将其与附件一起发送?
我的代码:
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
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
def send_message(message:str , subject:str, to_email:str, attachments: list=None):
"""Create and send an email message
Print the returned message id
Returns: Message object, including message id """
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
try:
service = build('gmail', 'v1', credentials=creds)
message = EmailMessage()
message.set_content(message)
# I added this part
if attachments:
for attachment in attachments:
with open(attachment, 'rb') as content_file:
content = content_file.read()
message.add_attachment(content, maintype='application', subtype= (attachment.split('.')[1]), filename=attachment)
message['To'] = to_email
message['From'] = 'gduser1@workspacesamples.dev'
message['Subject'] = subject
# encoded message
encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
create_message = {
'raw': message
}
# pylint: disable=E1101
send_message = (service.users().messages().send
(userId="me", body=create_message).execute())
print(F'Message Id: {send_message["id"]}')
except HttpError as error:
print(F'An error occurred: {error}')
send_message = None
return send_message
错误信息
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\generator.py", line 116, in flatten
self._write(msg)
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\generator.py", line 181, in _write
self._dispatch(msg)
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\generator.py", line 218, in _dispatch
meth(msg)
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\generator.py", line 362, in _handle_message g.flatten(msg.get_payload(0), unixfrom=False, linesep=self._NL)
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\generator.py", line 116, in flatten
self._write(msg)
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\generator.py", line 181, in _write
self._dispatch(msg)
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\generator.py", line 209, in _dispatch
main = msg.get_content_maintype()
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\message.py", line 594, in get_content_maintype
ctype = self.get_content_type()
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\message.py", line 578, in get_content_type
value = self.get('content-type', missing)
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\message.py", line 471, in get
return self.policy.header_fetch_parse(k, v)
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\policy.py", line 159, in header_fetch_parse if hasattr(value, 'name'):
File "C:\Users\Cosmo Staff\AppData\Local\Programs\Python\Python310\lib\email\headerregistry.py", line 205, in name
@property
File "c:\Users\Cosmo Staff\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_trace_dispatch_regular.py", line 469, in __call__
return None if event == 'call' else NO_FTRACE
RecursionError: maximum recursion depth exceeded in comparison
完整的终端已经分配了更多,但它的分配,所以我粘贴了最后几行
在您的脚本中, message
与def send_message(message:str, subject:str, to_email:str, attachments: list=None):
和message = EmailMessage()
一起使用。 我认为您当前问题def send_message(message:str, subject:str, to_email:str, attachments: list=None):
的原因是由于这个。
而且,我认为在create_message = {'raw': message}
,会发生错误。 因为message
不是 URL 安全 base64。 我认为在这种情况下,这里应该使用encoded_message
encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
的encoded_message。 我以为这将是您的第二期。
当这些点反映在你的脚本中时,它变成如下。
def send_message(messageBody:str , subject:str, to_email:str, attachments: list=None):
"""Create and send an email message
Print the returned message id
Returns: Message object, including message id """
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
try:
service = build('gmail', 'v1', credentials=creds)
message = EmailMessage()
message.set_content(messageBody)
# I added this part
if attachments:
for attachment in attachments:
with open(attachment, 'rb') as content_file:
content = content_file.read()
message.add_attachment(content, maintype='application', subtype= (attachment.split('.')[1]), filename=attachment)
message['To'] = to_email
message['From'] = 'gduser1@workspacesamples.dev'
message['Subject'] = subject
# encoded message
encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
create_message = {
'raw': encoded_message
}
# pylint: disable=E1101
send_message = (service.users().messages().send
(userId="me", body=create_message).execute())
print(F'Message Id: {send_message["id"]}')
except HttpError as error:
print(F'An error occurred: {error}')
send_message = None
return send_message
def send_message(message:str, subject:str, to_email:str, attachments: list=None):
message
消息被修改为messageBody
。 并且, create_message = {'raw': message}
被修改为create_message = {"raw": encoded_message}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.