Gmail api send with Postman - gmail

I am trying to send a mail using gmail API with POSTMAN, using POST Method
POST https://www.googleapis.com/upload/gmail/v1/users/example#gmail.com/messages/send
but I get an error below:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalidArgument"
"message": "Recipient address required"
}
],
"code": 400,
"message": "Recipient address required"
}
}
header is already putted Content-type: message/rfc822
I know that this has to be encoded into base64(web_safe), so I translated
"From: sender.example#gmail.com\r\n" +
"To: receiver.example#gmail.com\r\n" +
"Subject: Subject Example\r\n" +
"This is content: hope you got it\r\n"
I also replaced them to be web_safe
replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
so I got an base64 like below.
so I put raw in body of POST METHOD
{
"raw": "RnJvbTogc2VuZGVyLmV4YW1wbGVAZ21haWwuY29tDQpUbzogcmVjZWl2ZXIuZXhhbXBsZUBnbWFpbC5jb20NClN1YmplY3Q6IFN1YmplY3QgRXhhbXBsZQ0KVGhpcyBpcyBjb250ZW50OiBob3BlIHlvdSBnb3QgaXQNCg"
}
I used 'try this api' on google developers' site, and I could send it.
https://developers.google.com/gmail/api/v1/reference/users/messages/send
But with POSTMAN, I cannot.
Any help please?

This mean, data format is incorrect. You should try below method which perfectly worked for me.
I use below format.
From: <FROM#gmail.com>
To: <TO#gmail.com>
Subject: Test Email
Test
For testing purpose, I used https://ostermiller.org/calc/encode.html to 64encode above text message. So I will get encoded string as below
IEZyb206IDxGUk9NQGdtYWlsLmNvbT4KICAgIFRvOiA8VE9AZ21haWwuY29tPgogICAgU3ViamVjdDogVGVzdCBFbWFpbAogICAgCiAgICBUZXN0
Now in postman,
Gmail Rest API URL you have to use https://www.googleapis.com/gmail/v1/users/<YOUR#gmail.com>/messages/send
Content type should be json because you send json format in message body.
Content-Type: application/json
In body
{
"raw": "IEZyb206IDxGUk9NQGdtYWlsLmNvbT4KICAgIFRvOiA8VE9AZ21haWwuY29tPgogICAgU3ViamVjdDogVGVzdCBFbWFpbAogICAgCiAgICBUZXN0"
}
So finally postman looks like as below.
Once you send a request to API, You will receive response looks like this
{
"id": "172016110a227c19",
"threadId": "172016110a227c19",
"labelIds": [
"UNREAD",
"SENT",
"INBOX"
]
}

I think that you should set the Content-type header to application/json. Also, don't forget to add the Authorization header.

If you want more details please refer below link:
How to send a message successfully using the new Gmail REST API?

If you want more details please refer below link: Gmail API send message without using Base64 encode

Related

How can i get the call-sid from response of callback in twilios AddOn's "IBM Watson"

We enable the Twilios AddOn "IBM Watson Speech to Text" for recording transcribe.and we set our server webhook while enabling the addon. Now twilio calling webhook once call is completely done. after completing call twilio give response in that webhook In Nodejs.For handling that call response we need "Call Sid".In webhook response we cannot get "callSid".So how we can identify that response is for this particular call...?
anyone help me to how can find call-sid in response?
Callback response is
{
"status": "successful",
"message": null,
"code": null,
"results": {
"ibm_watson_speechtotext": {
"request_sid": "**************",
"status": "successful",
"message": null,
"code": null,
"payload": [{
"content_type": "application/json",
"url": "*************/Data"
}],
"links": {
"add_on_result": "***********/Accounts/********/Recordings/**********/AddOnResults/******",
"payloads": "https://api.twilio.com/2010-04-01/Accounts/******/Recordings/*******/AddOnResults/******/Payloads",
"recording": "https://api.twilio.com/2010-04-01/Accounts/******/Recordings/*******"
}
}
}
}
Thank you for help
When you get the Add-on result it comes as part of the Twilio voice webhook, with all the normal request parameters as well as an extra AddOns parameter which contains the JSON that you have shared above.
Webhook requests from Twilio are in the format application/x-www-form-urlencoded and then within the AddOns parameter the data is a JSON string. In a (Ruby-like) pseudo code, you can access the call sid and the add on data like this:
post "/webhook" do
call_sid = params["CallSid"]
add_on_json = params["AddOns"]
add_on_data = JSON.parse(add_on_json)
# return TwiML
end

How can I get the phone number from Twilio in fulfillment dialogflow

I'm working in a whastapp bot between Twilio and Dialogflow. In one of the intents, I'm sending media files from dialogflow to the user. Here it's the problem, now it's working with my mobile number hardcoded, but I need to access to the user phone number in each case to send the media file.
I develop this in fulfillment dialogflow, inline editor, using some nodejs code, but there I can't access to the user number.
Fulfillment node js
function sendAudioMensaje(agent) {
client.messages.create({
body: 'Body message',
to: 'whatsapp:+34---------', // Text to this number
from: 'whatsapp:+14155238886', // From a valid Twilio number
mediaUrl: 'https://demo.twilio.com/owl.png'
}).then((message) => agent.add(message.sid));
}
I expect that the message would be sent to the current number in each conversation
Twilio developer evangelist here.
As far as I can tell, the Dialogflow webhook request comes with a originalDetectIntentRequest property in the JSON. This contains a OriginalDetectIntentRequest object, which has a payload property that contains the original request.
I'd start by logging the contents of the webhook request to see what is fully available to you though.
Let me know if that helps at all.
In the payload of the OriginalDetectIntent request you will see a JSON like this in the webhook if it's enabled.
{
"source": "twilio",
"data": {
"SmsSid": "",
"Body": "",
"SmsStatus": "received",
"MessageSid": "",
"ApiVersion": "2010-04-01",
"From": "",
"AccountSid": "",
"NumMedia": "0",
"To": "",
"SmsMessageSid": "",
"NumSegments": "1"
}
}

getting 403 error while sending file to githib via REST using nodejs

I want to send multiple files to Github repository via nodejs. Tried several approaches and end up using node-rest-client module. Tried below code send a sample file to repository called 'metadata'. But after post I am getting error message "Request forbidden by administrative rules. Please make sure your request has a User-Agent header"...please let me know if anyone faced this error before and get rid of it.
convertval = "somedata";
var dataObj = {
"message": "my commit message",
"committer": {
"name": "Scott Chacon",
"email": "ravindra.devagiri#gmail.com"
},
"content": "bXkgbmV3IGZpbGUgY29udGVudHM="
}
debugger;
var Client = require('node-rest-client').Client;
var client = new Client()
var args = {
data: dataObj,
headers: { 'Content-Type': 'application/json' },
};
client.post("https://api.github.com/repos/metadata/contents", args, function (data, response) {
console.log("file send: True : " + data);
});
According to the REST API:
All API requests MUST include a valid User-Agent header. Requests with
no User-Agent header will be rejected.
First of all, you need to define 'User-Agent' with value 'request' in your request header. Refer to this link.
Second, endpoint you are trying to call might require authentication. Generate a personal token from here, add that token in your request header, 'Authorization': 'token '.
If you're using Git extensively in your code, I suggest you to use this - Nodegit.
Edit:
I don't think sending multiple files in a single request is possible in 'Contents' endpoints group (link).
You can checkout Git Data API (as discussed here).

Cannot fetch internet message headers for some emails

I'm using the Microsoft Graph Client for Node.js to fetch email messages. I'm only interested in the headers. The code is working, but recently I got some errors in fetching internetMessageHeaders via the API.
For some messages, the API doesn't return any data for this field (and the code wasn't checking for this, hence the errors).
I tried to manually run the queries using POSTMAN. Using ?$select=internetMessageHeaders as a query param to only fetch the headers. If I remove the query param, I can fetch the message normally (body, etc.).
I haven't been able to find anywhere in the docs why this would happen.
Any ideas on what it's happening?
Edit: Here is the node.js code I am using
const MicrosoftGraphClient = require("#microsoft/microsoft-graph-client").Client
async function fetchEmailMessageHeaders(id, credentials) {
let client = MicrosoftGraphClient.init({
authProvider: callback => callback(null, credentials.access_token)
});
let req = client.api(id).select("internetMessageHeaders");
let message = await req.get();
return message.internetMessageHeaders;
}
Sample output (value of message var):
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('156751349d3cc68b')/messages(internetMessageHeaders)/$entity",
"#odata.etag": "W/\"CQAAABYAAABcr9US8aH2RIGaOGQZwDg3AAKyfdpk\"",
"id": "AQMkADAwATM0MDAAMS1hZWIxLThjZmYALTAwAi0wMAoARgAAA3wcQrEUgfhHoZ0BD2jmyXYHAFyv1RLxofZEgZo4ZBnAODcAAAIBDAAAAFyv1RLxofZEgZo4ZBnAODcAArJaPEcAAAA=",
"internetMessageHeaders": [
{
"name": "Received",
"value": "from BY2NAM01HT225.eop-nam01.prod.protection.outlook.com (2603:10a6:803:118::39) by VI1PR0301MB2221.eurprd03.prod.outlook.com with HTTPS via VE1PR03CA0050.EURPRD03.PROD.OUTLOOK.COM; Wed, 10 Apr 2019 11:41:55 +0000"
}
...
]
}
The problem is that for some emails, the message does not contain internetMessageHeaders.
I am using an inbox subscription to receive events for new email messages from Outlook. When an event is received I use the API to retrieve the message and extract headers from it.
API reference here
Edit2:
Here is an example JSON output of an event that fails to also retrieve headers:
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('53e07bf4-bb6a-4a82-a724-37dadfb1cf11')/messages(internetMessageHeaders)/$entity",
"#odata.etag": "W/\"CQAAABQAAADdeU+v2VzbRpZMSJGral7kAAXJkA==\"",
"id": "AAMkADhmMmVmM2NjLWFhNGMtNDBlYy04NzBkLTg5MmU2OWI0ODU4MgBGAAAAAAALg6E-e6CxRLEbZfrhFaDBBwAzAAMgKF1iTp242t34rFy5AAAAAAAOAAB5l_O62bUUTqTLk6KYrl4sAAGrJcjfAAA="
}
It seems internetMessageHeaders are not set when an email is replied to using outlook.office365.com. I'm also not able to see message headers when inspecting the message using Outlook on Mac.

Attaching a file using Resumable upload w/ Gmail API

I am attempting to use Gmail's Resumable option for uploading attachments to an email. Documentation reference: https://developers.google.com/gmail/api/guides/uploads#resumable.
Currently I am able to send the email with the resumable URI, but without an attachment (using Postman). Documentation doesn't provide very clear examples of what the request should specifically look like, and there don't seem to be many examples after scouring the internet.
My requests are in two parts:
Initial request -
Request URL:
POST /upload/gmail/v1/users/me/messages/send?uploadType=resumable
Host: www.googleapis.c om (can't post links so I interrupted the url)
Headers:
Authorization: Bearer my_token_here
Content-Length: 113
Content-Type: application/json
X-Upload-Content-Length: 67
X-Upload-Content-Type: message/rfc822
Body:
{"raw":"VG86IG5pcnZhbmEucm9ja2VyQGdtYWlsLmNvbQpTdWJqZWN0OiBUZXN0RW1haWxTdWJqZWN0MwoKTWVzc2FnZSBjb250ZW50cyAjMy4"}
The body is a 64bit encoded string that include the To, Subject, and email message contents. Then gmail returns a response with an empty body, and a 'location' header that looks like the following: googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=resumable&upload_id=BRnB2UoAsKwzNMoQAy-JtmP6mu5agltqOWZ9uerI3k-KNTDJ73PWEjKuAHpko4RN6weSEysddH2kjj4G24uFw6E9oPv1XP69l7_KcmNuW-RAoz_5oS1T_4_E. (removed https:// because this account can only have one link in a post)
I then follow up with a PUT request to that URL returned in the location header.
The second request looks like the following:
Request URL:
PUT /upload/gmail/v1/users/me/messages/send?uploadType=resumable&upload_id=BRnB2UoAsKwzNMoQAy-JtmP6mu5agltqOWZ9uerI3k-KNTDJ73PWEjKuAHpko4RN6weSEysddH2kjj4G24uFw6E9oPv1XP69l7_KcmNuW-RAoz_5oS1T_4_E
Host: www.googleapis.c om
Headers:
Content-Length: 67
Content-Type: message/rfc822
Body:
{"raw":"VG86IG5pcnZhbmEucm9ja2VyQGdtYWlsLmNvbQpTdWJqZWN0OiBUZXN0RW1haWxTdWJqZWN0MwoKTWVzc2FnZSBjb250ZW50cyAjMy4"}
--- OR ---
I choose the binary option, and attach the file I am looking to upload via Postman.
I receive a response from Gmail with an object like this:
{
"id": "159d7ded3125e255",
"threadId": "159d7ded3125e255",
"labelIds": [
"SENT"
]
}
And an email is sent successfully, however there isn't an attachment with the email. When I show the original email in Gmail, there isn't any evidence of an attachment. Original looks like the following:
Received: from 325276275830 named unknown by gmailapi.google.com with HTTPREST; Wed, 25 Jan 2017 15:03:33 -0800
To: some.name#gmail.com
Subject: TestEmailSubject3
Date: Wed, 25 Jan 2017 15:03:33 -0800
Message-Id: <CEROA6F=0ohk33RD9XyC_gW1DZO88xYF4bXYqrCSct62MUuytDw#mail.gmail.com>
From: name_here#gmail.com
Message contents #3.
What am I missing? Do I need to encode some particular contents in a different way, or put some data in a different location? I'm not receiving any errors. I've been working on this for a few days now and I just can't figure it out.
I ran into the same problem, i made it work by using Nodemailer to create the email with the attachments, save the result to a file, then upload it with this.
Instead of send email in two parts you can send all your email data and attachment data as a mime message. like this.
I am using JavaScript client so you can do like this:
// MIME Mail Message data.
let mail = [
'Content-Type: multipart/mixed; boundary="foo_bar_baz"\r\n',
"MIME-Version: 1.0\r\n",
"to: to#gmail.com\r\n",
"from: from#gmail.com\r\n",
"subject: i am subject\r\n\r\n",
"--foo_bar_baz\r\n",
'Content-Type: text/plain; charset="UTF-8"\r\n',
"MIME-Version: 1.0\r\n",
"Content-Transfer-Encoding: 7bit\r\n\r\n",
"The actual message text goes here\r\n",
"--foo_bar_baz\r\n",
"Content-Type: application/json; name=package.json\r\n",
"Content-Transfer-Encoding: base64\r\n",
"Content-Disposition: attachment; filename=package.json\r\n\r\n",
"<base64 file data. data according to content type>",
"\r\n",
"--foo_bar_baz--",
].join("");
// get resumable upload link.
let resumableURL = "";
gapi.client
.request({
path: "/upload/gmail/v1/users/me/messages/send?uploadType=resumable",
headers: {
"X-Upload-Content-Type": "message/rfc822",
},
method: "post",
})
.then(
(res) => {
resumableURL = res.headers.location;
console.log(res);
},
(err) => console.log(err)
);
// send email
gapi.client
.request({
path: resumableURL,
headers: {
"Content-Type": "message/rfc822",
},
method: "post",
body: mail,
})
.then(
(res) => {
console.log(res);
},
(err) => console.log(err)
);
To convert gapi.client.request to Fetch API call you just need to add Authorization: Bearer <access_token> to header field. I have tried using Fetch API but response were blocked due to cors error so api client like Postman should be used.
To do more with resumable upload method check documentation: Upload Attachment

Resources