google-apps-scriptgoogle-email-migration

Email Migration API v2: Google Apps Script


I am trying to write a GAS to migrate some emails which are stored in Google Drive but I am really struggling to get the POST correct to do this and was hoping someone could help me out and steer me in the right direction.

What I have so far is ..

  var id = "12345678abcdefgh";
  var doc = DocumentApp.openById(id);
  var emlData = doc.getText();
  var api_scope = 'https://www.googleapis.com/auth/email.migration';
  var app_name = "migration";
  var userKey = "someone@mygappsdomain.com";
  var method = "POST";

  var url = "https://www.googleapis.com/upload/email/v2/users/"+userKey+"/mail?uploadType=multipart";


  var fields =  {"MailItem" : 
                  {"properties":
                   {'isInbox': 'true','isUnread': 'true'},
                   'labels': ['MigrateMe']}};

  var options = {payload: {data: JSON.stringify(emlData), fields: fields, contentType: 'multipart/related', boundary : 'part_boundary'}};
  var fetchArgs = googleOauth_(app_name,api_scope,method,options);
  try
  {
    var result = UrlFetchApp.fetch(url, fetchArgs).getResponseCode();
    Logger.log("done");
  }
  catch (ee) 
  {
    Logger.log(ee);
  }
}

This obviously doesn't work and I get a 400 error code. Do you know what could be wrong ?


Solution

  • As spoken in comment here an exemple to do it with the playground api:

    step 1:
    Authorise: https://www.googleapis.com/auth/email.migration

    step 2:
    Authorize blbablablabla (you know what to do here)

    step 3:
    You need to do a POST to hte URL:
    https://www.googleapis.com/upload/email/v2/users/EMAILADRESS@DOMAIN.EXT/mail

    The Content-type need to be set on: custom...
    and the arguments are:

    uploadType:media
    Content-Type:message/rfc822
    

    the request body must look at something like this:

    Date: Wed, 03 Jan 2013 02:56:03 -0800
    From: admin@example.org
    To: liz@example.com
    Subject: Hello World!
    MIME-Version: 1.0
    Content-Type: text/html; charset=windows-1252
    Content-transfer-encoding: 8bit
    
    And I think to myself... What a wonderful world!
    

    (you can take exactly this one to do some test and then in your mailbox search for "liz")

    If everything worked you should have something like this: enter image description here

    To do this I used the documentation found here:
    https://developers.google.com/admin-sdk/email-migration/v2/guides/upload
    https://developers.google.com/admin-sdk/email-migration/v2/reference/mail/insert

    This is not the solution to your post, but I Hope it will help you to get it! (and by the way if you get to have a nice working code please give the real answer to your question - I'm also interested)