Skip to content

Instantly share code, notes, and snippets.

@jacksonj04
Created October 28, 2014 15:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jacksonj04/60c1da79da8c86feea1b to your computer and use it in GitHub Desktop.
Save jacksonj04/60c1da79da8c86feea1b to your computer and use it in GitHub Desktop.
mbox to Google Groups
# Import a mbox file to a Google Group using https://developers.google.com/admin-sdk/groups-migration/index
# You'll need to install https://developers.google.com/api-client-library/python/
import mailbox
import time
import httplib2
import sys
import argparse
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import OAuth2WebServerFlow
from oauth2client import tools
from oauth2client.tools import run_flow
from apiclient.http import MediaInMemoryUpload
groupId = 'group@example.com' # The email address of the group to import to
# https://console.developers.google.com/project/mysociety-groups-import/apiui/credential
# Generate a Client ID for Native Application. You'll be prompted to complete an auth flow
# on the first run. The user will need to be an admin.
client_id = '123456'
client_secret = '123456'
scope = 'https://www.googleapis.com/auth/apps.groups.migration'
flow = OAuth2WebServerFlow(client_id, client_secret, scope)
parser = argparse.ArgumentParser(parents=[tools.argparser])
flags = parser.parse_args()
storage = Storage('credentials.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run_flow(flow, storage, flags)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('groupsmigration', 'v1', http=http)
mb = mailbox.mbox('archive.mbox') # The path of the mbox file to import
i = 1;
total_messages = len(mb)
for msg in mb:
media = MediaInMemoryUpload(msg.as_string(), mimetype='message/rfc822')
response = service.archive().insert(groupId=groupId,media_body=media).execute()
print 'Message %s of %s: %s' % (i, total_messages, response['responseCode'])
i = i + 1
time.sleep(1)
print 'Done.'
@willend
Copy link

willend commented Aug 12, 2017

Hi @jacksonj04,

I realise it is a while since you uploaded this gist... Hoping you might have an idea anyway?

My initial authentication seems to be set up OK, but all upload attempts end in an error 500 here... I've tried getting a little more debugging output by setting httplib2.debuglevel = 1 as suggested in https://stackoverflow.com/questions/36163375/getting-500-backend-error-when-using-google-groups-migration-api, but no help.

Best,
Peter

@pjsg
Copy link

pjsg commented Apr 18, 2018

@willend Did you ever figure out your problem -- I'm facing the same issue.....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment