我正面临着同样的问题: 创建草稿回复 然而,我不能使它工作。 总结一下,我试图创建一个草案电子邮件使用Python 3和gmail Api使用以下代码:
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient import errors
import base64
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
import os
from json import dumps
from apiclient import errors
SCOPES = ['https://www.googleapis.com/auth/gmail.compose']
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
service = build('gmail', 'v1', credentials=creds)
def create_message(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
#return {'raw': str(base64.urlsafe_b64encode(message.as_string()))}
return {'raw',base64.urlsafe_b64encode(message.as_string().encode("utf-8"))}
def create_draft(service, user_id, message_body):
try:
message = {'message': message_body}
draft = service.users().drafts().create(userId=user_id, body=message).execute()
print("Draft id: \n",draft['id'],"Draft message: ", draft['message'])
return draft
except Exception as e:
print(f"Error Occured: {e}")
return None
send_by = "from@gmail.com"
send_to = "to@gmail.com"
msg = create_message(send_by,send_to,'Re: Some Subject','This is a test')
create_draft(service,'me', msg)
然后我得到了误差: 错误发生:set类型的对象不是JSON序列化的 谢谢你的帮助,我完全被困住了 问题来源StackOverflow 地址:/questions/59382035/create-draft-mail-using-gmailapi
都要进行序列化处理的
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。