Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Google API Client Libraryを使って、PythonからGmailを送信
from __future__ import with_statement
import pickle
import webbrowser
import httplib2
import base64
from sys import exit
from email.mime.text import MIMEText
from oauth2client import client
from apiclient.discovery import build
from apiclient import errors
def retrieve_authorize_code(flow):
auth_url = flow.step1_get_authorize_url()
webbrowser.open(auth_url)
exit(0)
def retrieve_credential(flow):
#auth_code = "auth_code"
#credential = flow.step2_exchange(auth_code)
#with open("credential.pickle", "w") as fpickle:
# pickle.dump(credential, fpickle)
# load credential
with open("credential.pickle", "r") as fpickle:
credential = pickle.load(fpickle)
return credential
def create_service(credential):
http_auth = credential.authorize(httplib2.Http())
return build("gmail", "v1", http=http_auth)
def create_mail(message_text, subject, to, from_):
message = MIMEText(message_text)
message["subject"] = subject
message["to"] = to
message["from"] = from_
return {"raw": base64.urlsafe_b64encode(message.as_string())}
def send_mail(service, raw):
try:
message = service.users().messages().send(userId="me", body=raw).execute()
print "A message sent. Id: {}".format(message["id"])
except errors.HttpError, error:
print "An error occurred: {}".format(error)
"""Main"""
flow = client.flow_from_clientsecrets(
"client_secrets.json",
scope = "https://www.googleapis.com/auth/gmail.send",
redirect_uri = "urn:ietf:wg:oauth:2.0:oob")
# retrieve_authorize_code(flow)
credential = retrieve_credential(flow)
service = create_service(credential)
message_text = "hello, world!"
subject = "test subject"
to = "example@gmail.com"
from_ = "example@gmail.com"
mail = create_mail(message_text, subject, to, from_)
send_mail(service, mail)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment