本文介绍了以编程方式将草稿保存在 Gmail 草稿文件夹中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好使用 Python 或 Java,我想撰写一封电子邮件并将其保存到 gmail 草稿中,而无需用户干预,

Preferably using Python or Java, I want to compose an email and save it into gmail drafts without user intervention,

推荐答案

这是一个用于访问 Gmail 帐户的 Python 脚本.首先,您需要生成一个 OAuth 令牌.下载 Google 的xoauth.py 模块 并运行它.它将引导您完成这些步骤.您将获得一个 url 以获取验证码——将其粘贴到脚本中,它会吐出您的令牌和秘密:

Here's a Python script to access a Gmail account. First you need to generate an OAuth token. Download Google'sxoauth.py module and run it. It will walk you through the steps. You'll get a url to obtain a verification code -- paste this into the script and it will spit out your token and secret:

% python xoauth.py --generate_oauth_token [email protected]

获得令牌和机密后,将它们复制到下面的 Python 脚本中.它使用 xoauth.py 对 IMAP 客户端进行身份验证、连接到 IMAP、构建消息并将其放入草稿文件夹.

Once you've obtained your token and secret, copy them into the Python script below. It uses xoauth.py to authenticate the IMAP client, connects to IMAP, constructs a message and drops it into the Drafts folder.

import email.message
import imaplib
import random
import time
import xoauth

MY_EMAIL = '[email protected]'
MY_TOKEN = '<token>'
MY_SECRET = '<secret>'

# construct the oauth access token
nonce = str(random.randrange(2**64 - 1))
timestamp = str(int(time.time()))
consumer = xoauth.OAuthEntity('anonymous', 'anonymous')
access = xoauth.OAuthEntity(MY_TOKEN, MY_SECRET)
token = xoauth.GenerateXOauthString(
    consumer, access, MY_EMAIL, 'imap', MY_EMAIL, nonce, timestamp)

# connect to gmail's imap service.
imap = imaplib.IMAP4_SSL('imap.googlemail.com')
imap.debug = 4
imap.authenticate('XOAUTH', lambda x: token)

# create the message
msg = email.message.Message()
msg['Subject'] = 'subject of the message'
msg['From'] = MY_EMAIL
msg['To'] = MY_EMAIL
msg.set_payload('Body of the message')

# append the message to the drafts folder
now = imaplib.Time2Internaldate(time.time())
imap.append('[Gmail]/Drafts', '', now, str(msg))

imap.logout()

这篇关于以编程方式将草稿保存在 Gmail 草稿文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-16 06:20