OAuth 2.0 gmail send message - google-api

I am trying with API REST google to connect to gmail and send a message with this API using the information in a contact form for the new message.
The documentation is not clear enough.
I use javascript.
Does anyone have any idea where he managed to do that?
thank you in advance

You should try and familiarize yourself using the JavaScript Quickstart. This will helps you authorize your request using OAuth 2.0. Then use send(), this will send the specified message to the recipients.
Here is the code snippet for sending :
/**
* Send Message.
*
* #param {String} userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* #param {String} email RFC 5322 formatted String.
* #param {Function} callback Function to call when the request is complete.
*/
function sendMessage(userId, email, callback) {
// Using the js-base64 library for encoding:
// https://www.npmjs.com/package/js-base64
var base64EncodedEmail = Base64.encodeURI(email);
var request = gapi.client.gmail.users.messages.send({
'userId': userId,
'resource': {
'raw': base64EncodedEmail
}
});
request.execute(callback);
}
There are also references/tutorials with regards to sending messages using javascript and Gmail API.
Sending Emails with the Gmail JavaScript API
Working with the Gmail JavaScript API
You could also use Apps Script and deploy it as a web app then let handled the Apps script do the rest.
Hope this helps.

Related

How to reach previously read emails by using Spring Integration?

I am developing a dynamic and multiple IMAP channel listener application. For the purpose of effectiveness, I am not downloading the attachments inside mails, just getting the texts inside them. Also I am developing an endpoint to access that previously arrived mails and download & return that attachment in order not to download every attachment. So basically I am trying to download attachments only if there is a demand.
I am using ImapIdleChannelAdapter to listen mails inside integration flow. Here is my flow,
public ImapIdleChannelAdapter mailAdapter(ImapMailReceiver receiver) {
ImapIdleChannelAdapter imapAdapter = new ImapIdleChannelAdapter(receiver);
imapAdapter.setAutoStartup(true);
return imapAdapter;
}
public IntegrationFlow createMailFlow(GmailRecieverRequirements requirements, String clientID) {
return IntegrationFlow.from(
mailAdapter(gmailMailReceiver(requirements)))
.handle(getMailHandler())
.get();
}
My question is, how can I access those previously read mails in different time? I know Java Mail has Folder - UID structure to access mails via UIDs. Here is the link. However, I do not want to use javaMail inside my flow to save the UID. Is there any chance that I could reach UID of the mail inside the flow by Spring Integration? I am open to any other solution.
Thanks in advance
This is indeed low-level mail API functionality. Not sure what you mean with your do not want to use javaMail inside my flow, but we only can do that on demand fetching if we know the folder and message UID and with that respective API of the IMAPFolder:
/**
* Get the Message corresponding to the given UID. If no such
* message exists, <code>null</code> is returned.
*
* #param uid UID for the desired message
* #return the Message object. <code>null</code> is returned
* if no message corresponding to this UID is obtained.
* #exception MessagingException for failures
*/
public Message getMessageByUID(long uid) throws MessagingException;
The ImapIdleChannelAdapter can produce raw jakarta.mail.Message to let you to obtain its UID via UIDFolder.getUID(Message message) API.

chatbot: how to validate incoming requests from google hangouts

We've put together a google hangouts chat bot to provide some convenient functionality for our team. The bot is of the 'bot URL' variety, meaning that hangouts sends requests to an app endpoint and our app responds appropriately. At the moment, we're struggling to now validate the incoming requests from google. Each request has a bearer token in the Authentication header, but that JWT token does not validate. Both the php client library [https://github.com/googleapis/google-api-php-client] and the online validator [https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=] return the error 'invalid signature'
The google client php library's Google_AccessToken_Verify class has a verifyIdToken method which we use as described here in this example [https://github.com/GoogleCloudPlatform/php-docs-samples/blob/master/auth/src/auth_cloud_explicit.php]. We pass the path of our service account key file and the project ID into the google client constructor. Then we pass the incoming request's bearer token into the verifyIdToken method.
use Google_Client;
// inside a laravel controller with $request in scope
$bearer_token = $request->bearerToken();
$keyPath = FILE_LOCATION
$client = new Google_Client([
'keyFilePath' => $keyPath,
'projectId' => GCP_CLIENT_ID
]);
$payload = $client->verifyIdToken($bearer_token);
if(!empty($payload)){
return $this->call(ParseGoogleChatRequest::class, [$request]);
}else{
\Log::debug('bad token');
}
I expect the google client library to be able to validate a google JWT. This github issue [https://github.com/firebase/php-jwt/issues/175] reflects our experience implementing this approach. I would like to get some general guidance on which approach we should be using.
I figured out an acceptable solution with the help of another SO question. The google client library was already importing firebase/php-jwt, so I followed along the same lines as Jed from the question I linked to. Extracting the KID from the token, I used it to identify the correct public key from this url. Then I instantiated the php-jwt library and called the decode method on it, passing the required arguments. The decode method also verifies the signature and returns the components of the JWT on success.

Google API: use offline access token in javascript

I started a project using the Google API signin mixed with an angularJS+Firebase app.
What I would like to do is to be able to send an e-mail from one person to another programmatically.
Example: John is logged in, clicks on a button which sends an email to Rachel. But that email is sent using the stored token from Ted, not John's account.
It seems possible using the php library which is not an option here.
So far, I get the token easily using these few lines:
var GoogleAuth = gapi.auth2.getAuthInstance();
GoogleAuth.grantOfflineAccess({
scope: 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/drive https://mail.google.com/ profile email'
}).then(function(resp) {
console.log(resp);
this.storeToken(resp.code);
});
Is it actually possible ?
A quick search just got me results for php or about how you get a token with the JS library... not how to use it !
From my understanding you want to use a refresh token ( offline access ) to send an email from Ted's account via Javascript.
Sadly this is not possible client side. What your code gives you is a 'code' that you can send to your server using a $http.post () and trade with Google server side for a refresh token.
Here is a guide for how to change that code into a refresh token.
While you can do this client side it would involve exposing your client secret which you should never do.(https://developers.google.com/identity/sign-in/web/server-side-flow)
Every time John wants to send an email from Ted's account your application will have to send a request to your server that:
Sends a request to google with the refresh token and generates an access token (https://developers.google.com/identity/protocols/OAuth2WebServer#offline)
Sends a seccond request to google using the access token to send the email from Ted's account
I hope that this helped.

Saving Mandrill webhook to database

Im having trouble understanding how to process the data sent to my post route from the mandrill webhook.
I have set up my route and registered it in the mandrill settings. Sending a test from the dashboard works fine (webhook is triggered on send, open, and hard_bounce):
Route::post('/mailApi/webhooks', 'ContactController#postMandrill');
Currently, I'm just trying to ensure that I can receive the webhook and make sure that I understand the format.
I have created a function for in my ContactController for testing purposes:
public function postMandrill(){
$data = Input::get("mandrill_events");
$mandrill = new Mandrillemail;
$mandrill->event = $data;
$mandrill->msg_subject = 'test';
$mandrill->save();
}
When I send an email to trigger the webhook, I get no errors and nothing is saved in the database. It seems like the route isn't touched at all. What do I need to do to access the webhook?

Authorizing Application Access to BigQuery without User Interaction, via PHP

I have a website, that does the simple work of fetching an USN from Google BigQuery on the cloud. Now, while accessing each time, I need to have a Google Account and also that particular email-id, should have the "permission" assigned in the "Team tab". I basically want the website to be available to everyone. And i am using PHP, so I need help about the functions that will be useful here.
The best way to build an application that is authorized to access the BigQuery API (as opposed to requiring a user authorization step) is to use OAuth2 service accounts. Essentially, a service account authorization provides certificate-based authorization for "server to server" interactions (such as your server side PHP script interacting with the BigQuery API).
There is documentation for using the Google PHP Client library with service account authorization here.
You have to create a 'service account' through google console and download the private key file (.p12) on your server. And use following code
/**
* setup service client using key file
* #param String $keyFileLoc location of .p12 file provided in google console
* #param String $clientEmail client location provided in google console
*/
function setupServiceClient($keyFileLoc,$clientEmail){
$client = new Google_Client();
$service = new Google_Service_Bigquery($client);
$client->setApplicationName("My Application Name");
$key = file_get_contents($keyFileLoc);
$cred = new Google_Auth_AssertionCredentials(
$clientEmail,
array('https://www.googleapis.com/auth/bigquery'),
$key
);
$this->client->setAssertionCredentials($cred);
return $service;
}

Resources