Skip to content

Instantly share code, notes, and snippets.

@walkure
Created May 26, 2021 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkure/e06b5e04b250fbff2dd0d116a9eb661a to your computer and use it in GitHub Desktop.
Save walkure/e06b5e04b250fbff2dd0d116a9eb661a to your computer and use it in GitHub Desktop.
XOAUTH2対応のIMAP転送スクリプト Python雑移植
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import imaplib
from oauthlib.oauth2 import BackendApplicationClient
import urllib.request
import json
import datetime
client_id = 'OAuth2 ID'
client_secret = 'OAuth2 Secret'
token_url = 'https://accounts.google.com/o/oauth2/token'
refresh_token="XOAuth2 Refresh Token"
mailaddr= 'GMailアドレス'
folder = 'INBOX'
if len(sys.argv) > 1:
folder = sys.argv[1]
class IMAP4_SSL(imaplib.IMAP4_SSL):
"""IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH2."""
def authenticate(self, username, access_token):
return imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH2',
lambda x: 'user={0}\1auth=Bearer {1}\1\1'.format(username, access_token))
def get_access_token():
oauth = BackendApplicationClient(client_id)
url, headers, body = oauth.prepare_refresh_token_request(token_url, client_id=client_id,
client_secret=client_secret,refresh_token=refresh_token)
req = urllib.request.Request(url, body.encode('us-ascii'), headers=headers)
with urllib.request.urlopen(req) as res:
obj = json.loads(res.read().decode())
return obj['access_token']
def insert_imap():
conn = IMAP4_SSL('imap.googlemail.com')
#conn.debug = 4
#print(conn.capability())
conn.authenticate(mailaddr,get_access_token())
rawmail = sys.stdin.read().encode('us-ascii')
conn.append(folder,[],datetime.datetime.now(datetime.timezone.utc),rawmail)
conn.logout()
insert_imap()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment