开发者社区> 问答> 正文

使用gmailApi创建草稿邮件?

我正面临着同样的问题: 创建草稿回复 然而,我不能使它工作。 总结一下,我试图创建一个草案电子邮件使用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

展开
收起
kun坤 2019-12-27 17:20:07 630 0
1 条回答
写回答
取消 提交回答
  • 技术架构师 阿里云开发者社区技术专家博主 CSDN签约专栏技术博主 掘金签约技术博主 云安全联盟专家 众多开源代码库Commiter

    都要进行序列化处理的

    2019-12-28 13:49:27
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载