Sending big email using Google PHP API client and gmail

If you start with the Google PHP api client, things are pretty ok.
The package lacks good documentation, and the examples provided are very basic.
But, you probably get it working and you start to write code to send email using the gmail API:

Now this code will work. But soon the user will add an attachment to this email, making it bigger than 5MB and BOOM it breaks.
As usual when you get stuck you open a browser, and search stackoverflow and google. You will find out more people have hit this problem, and some say it is fixed by using 'chunked uploads' ...
After hours of searching you give up and revert to using plain old SMTP as there is no documentation or anything telling you how to do this chunked upload.
Until now, as I will show you how to fix this.

I will implement only one way of sending email: using gmail API and using chunked uploads. Even if the mail is only a couple of characters like 'I will be late for dinner, start without me. Cheers'
Why? Because this small email will be send using 1 chunk, and it keeps it simple: there's no nasty if statements for smaller and bigger emails.

First, the changed code from the sample above:

So, what did we do?
First, we created, like before, an RFC 822 mail message in the variable $mailMessage, setup the Google API client, Created a gmail service instance and gmail message object etc.
Then, we told the Google_Client to not immediately do it's calls, but defer it until we actually start sending data to it. We also reset this at the end so we can do more calls from there that will be run immediatelly.
Then we started a MediaFileUpload which can be told to do it in chunks.
Then we simply start sending chunks until all data is uploaded, and continue our script as before.

Easy right? If only the documentation showed how to do this for something else than a file upload to Google Drive, it would have been easy.
But like I said before, the documentation of this package is mostly non-existing and you will need to read most of it's source before you understand how things work.

I hope I helped you a bit and saved you some hours of reading the internet.


Back to Top