Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get decoded attachment file size with gmail API

I am using google's php client library to talk to the gmail api.

I am attempting to report the file size of an attachment using this API.

I to test this, I sent myself an email with an attachment. I knew the size of this attachment to be 511KB. The gmail web ui reports this attachment as 499KB, which I suppose is close enough:

499KB image

When I fetch this image using the gmail json api, however, I do get the correct attachment size:

GET https://www.googleapis.com/gmail/v1/users/me/messages/14ef5015d08312fd/attachments/ANGjdJ-Yy2H2avT5aFV7akMM2Lp4NigSpHqKgMT48zUMPVe3l6B9U0cfs-jXYD3cWJPhEwVjXQxNg2ZGDBFXKpMnf1HbpoBCwzcuOYSAJmHBbMHGANWKynofHf5GyStvjHhvNpA5xwla2hj7zdm6SVISoMgAR-dHJIPXbRniHVdryv13bxNsUeuRFvYbktnAcIwi-ppD6C1VAJtnGQYIKtNjsOa68hOlMSGLByWOrbB2txEN_P4cM43U7SEEzFmIDjFhKGkEIiU1rvrf9WT8KFVTsJ1U9_nTFjfkXIjl_Q?key={YOUR_API_KEY}

returns

{
 "size": 510808,
 "data": "encoded_data_string_uiasd82187"
}

So there is a slight disconnect between what the gmail web UI shows and what the actual size of the attachment is. But here's where it gets weird:

When I make a request for the whole message (not just the attachment) aka, a request like this:

GET https://www.googleapis.com/gmail/v1/users/me/messages/14ef5015d08312fd?key={YOUR_API_KEY}

I get a json response like this:

"body": {
     "attachmentId": "ANGjdJ9P-2Q_1lMch1_smv_ZKACDE_QRtBisZ8bAWP1x_-ze8tvQiQunNCjcWUDkv2kjZo67AETe6Zmti5YZ3Zl4-EyaNtbtfxWOHBhTqQFSK673hZhEWW8Bg7Ul4ws2eOSYXrZsvWY8NhLptXJP5PM0W30LZk2sHj4XLWlmU64YxMPAOXwLOT1FeNc3EgVvlKJFQv1sUVajmA6c1K_qKgH_Y_c56fSJAz9aFRoh9RW6wvkhTV5NeLm9WFghkzpInwz6cm-DyJQhY-eOZLE2mvqQ4EmCPmBgzwNDh29mqQ",
     "size": 699004
    }

So the attachment with the ID that I'm looking for seems to have a size of 699KB, NOT the 511KB true size. This seems to be the size of the encoded attachment rather than the raw file.

So, using the PHP client library, when I have a Google_Service_Gmail_MessagePart representing this attachment, and I call $messagepart->getBody()->getSize() this returns 699004.

What I need is the true size of the attachment, 510808.

How can I get this true size, and is there a bug in the gmail API showing the wrong size in this context?

like image 366
johncorser Avatar asked Nov 09 '22 08:11

johncorser


1 Answers

That's the downside of base64-encoding, I'm afraid.

Very roughly, the final size of Base64-encoded binary data is equal to 1.37 times the original data size + 814 bytes (for headers). The size of the decoded data can be approximated with this formula:

bytes = (string_length(encoded_string) - 814) / 1.37

Wikipedia

This fits your example very well (511 * 1.37 ≈ 700).

like image 165
Tholle Avatar answered Nov 14 '22 23:11

Tholle