0

I am able to upload emails which doesn't have any attachments, but i am not able to upload emails which has attachments.

Is there any source where i can view the source code on how to do that?

Or can provide me any pointers / code stub using which i can complete the project?

I am currently using Nuget library with Visual studio 2010.

Following is my code which did not work :

 private Task Run()
 {
 UserCredential cred;
 cred = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
            {
                ClientId = "ClientID",
                ClientSecret = "ClientSecret",
            }, new[] { Google.Apis.Admin.email_migration_v2.AdminService.Scope.EmailMigration },  "admin@example.com", System.Threading.CancellationToken.None,new FileDataStore("Email.Migration")).Result;

var service = new AdminService(new Google.Apis.Services.BaseClientService.Initializer
            {
                ApplicationName = "Email Migration",
                HttpClientInitializer = cred 
            });

       return UploadFileAsync(service);
 }   

private Task<IUploadProgress> UploadFileAsync(AdminService service)
    { 
MailItem mailitem = new MailItem(); 
mailitem.IsInbox = true;

String BodyContent = String.Empty;

BodyContent = BodyContent + "--part_boundary \r\n";
BodyContent = BodyContent + "Content-Type: message/rfc822 \r\n";
BodyContent = BodyContent + "\r\n";
BodyContent = BodyContent + "Date: Wed, 03 Jan 2013 02:56:03 -0800 \r\n";
BodyContent = BodyContent + "From: admin@example.org \r\n";
BodyContent = BodyContent + "To: liz@example.com \r\n";
BodyContent = BodyContent + "Subject: Hello World! \r\n";
BodyContent = BodyContent + "MIME-Version: 1.0 \r\n";
BodyContent = BodyContent + "Content-Type: multipart/mixed; boundary=frontier \r\n";
BodyContent = BodyContent + "\r\n";
BodyContent = BodyContent + "--frontier \r\n";
BodyContent = BodyContent + "Content-Type: text/plain; charset=windows-1252 \r\n";
BodyContent = BodyContent + "Content-Transfer-Encoding: 8bit \r\n";
BodyContent = BodyContent + "\r\n";
BodyContent = BodyContent + "And I think to myself... What a wonderful world! \r\n";
BodyContent = BodyContent + "\r\n";
BodyContent = BodyContent + "--frontier \r\n";
BodyContent = BodyContent + "Content-Type: text/plain; name=\"test.txt\" \r\n";
BodyContent = BodyContent + "Content-Disposition: attachment; filename=\"test.txt\" \r\n";
BodyContent = BodyContent + "Content-Transfer-Encoding: 8bit \r\n";
BodyContent = BodyContent + "\r\n";
BodyContent = BodyContent + "Hello A! \r\n";
BodyContent = BodyContent + "\r\n";
BodyContent = BodyContent + "--frontier-- \r\n";
BodyContent = BodyContent + "\r\n";
BodyContent = BodyContent + "--part_boundary--";

byte[] byteArray = Encoding.UTF8.GetBytes(BodyContent);
MemoryStream stream = new MemoryStream(byteArray);

String ContentType = "multipart/related; boundary=\"part_boundary\"";

  var insert = service.Mail.Insert(mailitem, "abc@example.com", stream, ContentType);
        insert.ProgressChanged += new Action<Google.Apis.Upload.IUploadProgress> (irm_ProgressChanged);
        insert.ChunkSize = MailResource.InsertMediaUpload.DefaultChunkSize * 2;
        var task = insert.UploadAsync();
        task.ContinueWith(t =>
        {
            // NotOnRanToCompletion - this code will be called if the upload fails

        }, TaskContinuationOptions.NotOnRanToCompletion);
        task.ContinueWith(t =>
        {

            stream.Dispose();

        });
        return task;
   }

    private void irm_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
    {
        try
        {
            if (progress.Exception != null)
            {
                MessageBox.Show(progress.Exception.Message);  
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Below is Fiddler Stack trace :

    **IF set ContentType = multipart/related; boundary="part_boundary"**

    REQUEST----------------------

    POST https://www.googleapis.com/upload/email/v2/users/abc%40example.com/mail?uploadType=resumable HTTP/1.1
    User-Agent: Email Migration google-api-dotnet-client/1.8.1.31685 (gzip)
    X-Upload-Content-Type: multipart/related; boundary="part_boundary"
    X-Upload-Content-Length: 570
    Authorization: Bearer ya29.eAAnFji2cG-AUB0AAABy4_I8vQFWmALqA9718djCOPL1Wwkl_iWk3WrK5PGoMQ
    Content-Type: application/json; charset=utf-8
    Host: www.googleapis.com
    Content-Length: 36
    Accept-Encoding: gzip, deflate
    Connection: Keep-Alive

    {"isInbox":true,"labels":["SANKET"]}


    RESPONSE------------

    HTTP/1.1 400 Bad Request
    Content-Type: application/json; charset=UTF-8
    Content-Length: 373
    Date: Sat, 06 Sep 2014 13:30:09 GMT
    Server: UploadServer ("Built on Aug 18 2014 11:58:36 (1408388316)")
    Alternate-Protocol: 443:quic

    {
     "error": {
      "errors": [
       {
        "domain": "global",
        "reason": "badContent",
        "message": "Media type 'multipart/related; boundary=\"part_boundary\"' is not supported. Valid media types: [message/rfc822]"
       }
      ],
      "code": 400,
      "message": "Media type 'multipart/related; boundary=\"part_boundary\"' is not supported. Valid media types: [message/rfc822]"
     }
    }


    **if Set content-type = message/rfc822 then Two Requests** 

    1)  Request---------------

    POST https://www.googleapis.com/upload/email/v2/users/abc%40example.com/mail?uploadType=resumable HTTP/1.1
    User-Agent: Email Migration google-api-dotnet-client/1.8.1.31685 (gzip)
    X-Upload-Content-Type: message/rfc822
    X-Upload-Content-Length: 570
    Authorization: Bearer ya29.eAAnFji2cG-AUB0AAABy4_I8vQFWmALqA9718djCOPL1Wwkl_iWk3WrK5PGoMQ
    Content-Encoding: gzip
    Content-Type: application/json; charset=utf-8
    Host: www.googleapis.com
    Content-Length: 56
    Accept-Encoding: gzip, deflate
    Connection: Keep-Alive

    ‹ ]T ÿ«VÊ,öÌKʯP²*)*MÕQÊILJÍ)V²ŠV
    vôóv
    QŠ­ ']P±$   

    Response------------

    HTTP/1.1 200 OK
    Location: https://www.googleapis.com/upload/email/v2/users/abc@example.com/mail?uploadType=resumable&upload_id=AEnB2Ur3Nntr-eZT-K5-XoPDw2imWeMGylmY1SvOYr_ThmgDSkQBWe6gbxBy_fweqlRZPb_akwhwq2JZU9sy2NCWTvXdC6dr4A
    Cache-Control: no-cache, no-store, max-age=0, must-revalidate
    Pragma: no-cache
    Expires: Fri, 01 Jan 1990 00:00:00 GMT
    Date: Sat, 06 Sep 2014 13:41:06 GMT
    Server: UploadServer ("Built on Aug 18 2014 11:58:36 (1408388316)")
    Content-Length: 0
    Content-Type: text/html; charset=UTF-8
    Alternate-Protocol: 443:quic


    2) Request ----------------------------

    PUT https://www.googleapis.com/upload/email/v2/users/abc@eaxmple.com/mail?uploadType=resumable&upload_id=AEnB2Ur3Nntr-eZT-K5-XoPDw2imWeMGylmY1SvOYr_ThmgDSkQBWe6gbxBy_fweqlRZPb_akwhwq2JZU9sy2NCWTvXdC6dr4A HTTP/1.1
    User-Agent: Email Migration google-api-dotnet-client/1.8.1.31685 (gzip)
    Authorization: Bearer ya29.eAAnFji2cG-AUB0AAABy4_I8vQFWmALqA9718djCOPL1Wwkl_iWk3WrK5PGoMQ
    Content-Range: bytes 0-569/570
    Host: www.googleapis.com
    Content-Length: 570
    Accept-Encoding: gzip, deflate

    --part_boundary
    Content-Type: message/rfc822

    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: multipart/mixed; boundary=frontier

    --frontier
    Content-Type: text/plain; charset=windows-1252
    Content-Transfer-Encoding: 8bit

    And I think to myself... What a wonderful world!

    --frontier
    Content-Type: text/plain; name="test.txt"
    Content-Disposition: attachment; filename="test.txt"
    Content-Transfer-Encoding: base64

    SGVsbG8gQSE=

    --frontier--

    --part_boundary--


    Response :----------------

    HTTP/1.1 400 Bad Request
    Content-Type: application/json; charset=UTF-8
    Content-Length: 172
    Date: Sat, 06 Sep 2014 13:41:11 GMT
    Server: UploadServer ("Built on Aug 18 2014 11:58:36 (1408388316)")
    Alternate-Protocol: 443:quic

    {
     "error": {
      "errors": [
       {
        "domain": "global",
        "reason": "invalid",
        "message": "Invalid Input"
       }
      ],
      "code": 400,
      "message": "Invalid Input"
     }
    }

1 Answers1

-1

The source code is available here

I see that you're already using this, and you followed these

BUT.. can you please attach the exact error you're getting and fiddler stack trace?

Ramaraj T
  • 5,184
  • 4
  • 35
  • 68
peleyal
  • 3,472
  • 1
  • 14
  • 25
  • Error is 400 bed request when checked with irm.get progress() method. If I remove all boundary portion and attachment portion from content stream then mail upload end successfully in gmail account – Tejesh Patel Sep 04 '14 at 18:32
  • Can you give me please sample code in c# which migrate email with attachment using your nuget library – Tejesh Patel Sep 04 '14 at 18:40
  • It's an open source project, I can't create a sample code for each API (we have more than 70 APIs), but you should take a look in the drive sample for uploading media which is available at https://code.google.com/p/google-api-dotnet-client/source/browse/Drive.Sample/Program.cs?repo=samples#119 – peleyal Sep 04 '14 at 20:29
  • Okay, But at least, can you tell me please what is wrong in my above mentioned code? – Tejesh Patel Sep 05 '14 at 03:56
  • 1) I wouldn't change DefaultExponentialBackOffPolicy. 2) Take a look in https://code.google.com/p/google-api-dotnet-client/source/browse/Drive.Sample/Program.cs?repo=samples#130, and try to do similar thing and DON'T CREATE NEW MAILRESOURCE, try to use the insert method on the resource instead, something like: serivce.Mails.Insert(... 3) Try to insert other content type (not message/ref822), try to use different content,... – peleyal Sep 05 '14 at 22:58
  • Changed code as per your above comments but still error appear like 400 Bad Request. i also tried with different stream content. – Tejesh Patel Sep 06 '14 at 06:07
  • same stream content works in Google Play Ground but did not work with .NET library. – Tejesh Patel Sep 06 '14 at 06:13
  • Hello Peleyal, I added Fiddler Stack trace in above Question Details.Please see and let me know what is wrong. i am waiting for your reply. – Tejesh Patel Sep 09 '14 at 04:05
  • Thanks for help but we are able to resolving it – Tejesh Patel Sep 09 '14 at 13:57
  • Did you solve it? If so - please update the thread and explain how. THANKS – peleyal Sep 10 '14 at 15:21