title: Server-side OAuth for user impersonation via GMail API
body: <p>I am trying to perform server-side OAuth so I can use a specific user account in my domain to send emails (hence using GMail API) via my application.</p>
  
  <p>Mine is a purely server-side app and I cannot perform "user consent" via a UI.</p>
  
  <p>I have created a project in Google App Engine and have obtained service account credentials (P12 key).</p>
  
  <p>My code looks like this -</p>
  
  <pre><code>new GoogleCredential.Builder()
    .setTransport(httpTransport)
    .setJsonFactory(JSON_FACTORY)
    .setServiceAccountId(googleEmailerServiceAccountId)
    .setServiceAccountPrivateKeyFromP12File(new File(googleEmailerServiceAccountPrivateKeyLocation)).setServiceAccountScopes(Collections.singleton(GmailScopes.GMAIL_COMPOSE))
    .setServiceAccountUser("xxx@xxx.com")
    .build()
  </code></pre>
  
  <p>I have delegated domain wide access to the application (for GMAIL COMPOSE scope) via the admin console as per <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount" rel="nofollow">https://developers.google.com/identity/protocols/OAuth2ServiceAccount</a>.</p>
  
  <p>And I still get an Unauthorised 401 when I try to send emails from my app.</p>
  
  <p>Since there is no explicit documentation for the Gmail API that says it allows domain wide delegation, I am guessing it is not allowed for Gmail.</p>
  
  <p>Is there any way of achieving this programatically? </p>
  
  <p>Any idea would be much appreciated.
  Thanks!</p>