这是一个用于访问Gmail帐户的Python脚本.首先,您需要生成OAuth令牌.下载Google的xoauth.py模块并运行它.它将指导您完成各个步骤.您将获得一个获取验证码的网址 - 将其粘贴到脚本中,它会吐出您的令牌和密码:
% python xoauth.py --generate_oauth_token --user=youremail@gmail.com
Run Code Online (Sandbox Code Playgroud)
获得令牌和秘密后,将它们复制到下面的Python脚本中.它用于xoauth.py验证IMAP客户端,连接到IMAP,构造邮件并将其放入Drafts文件夹.
import email.message
import imaplib
import random
import time
import xoauth
MY_EMAIL = 'youremail@gmail.com'
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3743 次 |
| 最近记录: |