How does the body of the request look like when making a call to gmail api for sending an email with attachment (multipart)? - email

Google documentation gave an example as below:
POST /upload/gmail/v1/users/userId/messages/send?uploadType=multipart HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer your_auth_token
Content-Type: multipart/related; boundary=foo_bar_baz
Content-Length: number_of_bytes_in_entire_request_body
--foo_bar_baz
Content-Type: application/json; charset=UTF-8
{
"id": string,
"threadId": string,
"labelIds": [
string
],
"snippet": string,
"historyId": unsigned long,
"payload": {
"partId": string,
"mimeType": string,
"filename": string,
"headers": [
{
"name": string,
"value": string
}
],
"body": users.messages.attachments Resource,
"parts": [
(MessagePart)
]
},
"sizeEstimate": integer,
"raw": bytes
}
--foo_bar_baz
Content-Type: message/rfc822
Email Message data
--foo_bar_baz--
If the request succeeds, the server returns the HTTP 200 OK status code along with any metadata:
HTTP/1.1 200
Content-Type: application/json
{
"id": string,
"threadId": string,
"labelIds": [
string
],
"snippet": string,
"historyId": unsigned long,
"payload": {
"partId": string,
"mimeType": string,
"filename": string,
"headers": [
{
"name": string,
"value": string
}
],
"body": users.messages.attachments Resource,
"parts": [
(MessagePart)
]
},
"sizeEstimate": integer,
"raw": bytes
}
Can someone make a sample request body by looking at the above example?
I need to send an email with attachment.

Based from SO related post, the body request can be something like this:
var mail = [
'Content-Type: multipart/mixed; boundary="foo_bar_baz"\r\n',
'MIME-Version: 1.0\r\n',
'From: sender#gmail.com\r\n',
'To: receiver#gmail.com\r\n',
'Subject: Subject Text\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\r\n',
'--foo_bar_baz\r\n',
'Content-Type: image/png\r\n',
'MIME-Version: 1.0\r\n',
'Content-Transfer-Encoding: base64\r\n',
'Content-Disposition: attachment; filename="example.png"\r\n\r\n',
pngData, '\r\n\r\n',
'--foo_bar_baz--'
].join('');
var response = UrlFetchApp.fetch(
"https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=media", {
method: "POST",
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken(),
"Content-Type": "message/rfc822",
},
muteHttpExceptions: true,
payload: mail
});
Here's also an example code from digital inspiration written by Amit Agarwal in Google Appscript.
This example shows how you can easily send email messages with file attachment using Gmail API.

Related

Wiremock to remove additional data (meta-data) in response

I am trying to post a file in wiremock and configure the file in mapping like below. And in the response I am seeing Content-Type, Content-Disposition etc, is there a way to disable this?
POST file
http://localhost:8080/__admin/files/some.json
used form-data to upload the file
contents of some.json
{
"user": "xxx"
}
To create mapping
http://localhost:8080/__admin/mappings
{
"request": {
"method": "GET",
"url": "/some"
},
"response": {
"status": 200,
"bodyFileName": "some.json",
"headers": {
"Content-Type": [
"application/json;charset=UTF-8"
]
}
}
}
To check the api
http://localhost:8080/some
Response:
----------------------------228585284577179878202292
Content-Disposition: form-data; name="file"; filename="some.json"
Content-Type: application/json
{
"user": "xxx"
}
----------------------------228585284577179878202292--
Like you see, there are additional content like below to the actual response. Wanted to disable the below. How to do this?
----------------------------228585284577179878202292
Content-Disposition: form-data; name="file"; filename="some.json"
Content-Type: application/json
----------------------------228585284577179878202292--
Instead of form-data choose binary while uploading the file. Then it return only the actual response...
{
"user": "xxx"
}
If you put a file by HTTP request to wiremock instance, as #Minisha said, add 'Content-type': 'binary' header to your put request. Here is an example with python requests:
headers = {'Content-type': 'binary'}
requests.put(url=mock_wire_files_url_file_name, data=open(your_file, 'rb'), headers=headers)

im fairly new and facing a problem about sending api request

I'm fairly new to the swift and I'm facing a problem with Alamofire what I'm trying to do is sending a get request with json body but I'm stuck heres my code:
struct request {
func getMessage(message:String){
let parameters: [String:Any] = [
"message" : [
"text": message,
"type":"text"
],
"type":"message",
"recipentId":"",
"info": [
"token":""
]
]
makeRequest(parameters: parameters)
}
func makeRequest(parameters:[String:Any]){
AF.request("https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944",method: .post,parameters: parameters).response{
response in
debugPrint(response)
}
}
after executing this code i get:
[Request]: POST https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944
[Request Body]:
info%5Btoken%5D=&message%5Btype%5D=text&message%5Btext%5D=Karakter&recipentId=&type=message
[Response]:
[Status Code]: 415
[Headers]:
Accept: application/json
Content-Length: 0
Date: Sat, 07 Mar 2020 19:10:23 GMT
Server: cloudflare
cf-cache-status: DYNAMIC
cf-ray: 57069dc3eaccad06-OTP
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
x-b3-traceid: b10ba988c0249901
[Response Body]:
None
[Data]: None
[Network Duration]: 0.3303520679473877s
[Serialization Duration]: 0.0s
[Result]: success(nil)
i dont get any result body compared to what expect when i send this request over postman:
"result": {
"messages": [
{
"type": "text",
"text": "Karakter Analizine Hoşgeldiniz. Analize başlamak için \"karakter\" yazınız"
},
{
"type": "text",
"text": "Test"
}
],
"tag": [
"start",
"finish"
],
"conversation_id": "5e63f302dc4bec0001883f01",
"intent_name": "Default Karakter",
"intent_id": "5ccb46ef66d0ba0001dbfcdf",
"intent_score": null,
"current_flow_id": "ee52db21-dae1-4587-80cd-7649798dddce1583608578222"
}
so how can i send this post request with this given body below:
let parameters: [String:Any] = [
"message" : [
"text": message,
"type":"text"
],
"type":"message",
"recipentId":"",
"info": [
"token":""
]
]
Now i have sent the request and got a body looking like this:
"result": {
"messages": [
{
"extra": {},
"question": "Adınız ?",
"type": "text",
"values": [
{
"text": ""
}
],
"askCount": 1,
"text": "Adınız ?",
"waitUserInput": true
}
],
"tag": [
"start",
"p_firstName",
1
],
"conversation_id": "5e63ffa0dc4bec0001883f10",
"intent_name": "Karakter Analizi",
"intent_id": "5cc20ae266d0ba0001dbf946",
"intent_score": "62.0",
"current_flow_id": "62ac3ac8-0cd7-43e5-b92b-f119d49c40d41583611808850"
}
how can i print the question variable to a label on my screen ?
Response code 415 means Unsupported Media Type and the Accept header of the response lets you know that the sever expects data to be sent as JSON. All you have to do is to let Alamofire know that it should encode parameters as JSON in the request body
AF.request("https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944",
method: .post,
parameters: parameters,
encoding: JSONEncoding.default).response { response in
debugPrint(response)
}
you need to mention the encoding type as well while sending request. since your parameters data is json add encoding parameter as encoding: JSONEncoding.default
for example i have used as:
manager.request(url, method: httpMethod,
parameters: parameters,
encoding: JSONEncoding.default,
headers: configuredHeader)
.validate(statusCode: 200..<300)
.responseJSON(completionHandler: { [weak self] response in
self?.handleNetworkResponse(response: response, networkCompletionHandler: networkCompletionHandler)
})

REST Client extension not sending form-data in VSCode

I'm attempting to POST Authenticate using REST Client in vscode, but it isn't accepting my form-data. This is the http code from postman which appears to match specs on https://marketplace.visualstudio.com/items?itemName=humao.rest-client but I don't understand why it doesn't like my credentials when submitting from vscode. Any help or pointers greatly appreciated.
Request:
POST /myservicestack/authenticate/credentials HTTP/1.1
Host: services.mydomain.com
Accept: application/json
cache-control: no-cache
Postman-Token: cdax7d61-8d8b-4f3q-b45v-74a240f33693
Content-Disposition: form-data; name="UserName"
myemail#address.com
Content-Disposition: form-data; name="Password"
My Password!
Content-Disposition: form-data; name="RememberMe"
true
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Response:
{
"responseStatus": {
"errorCode": "ValidationException",
"message": "Validation failed: \r\n -- 'User Name' should not be empty.\r\n --
'Password' should not be empty.",
"errors": [
{
"errorCode": "NotEmpty",
"fieldName": "UserName",
"message": "'User Name' should not be empty.",
"meta": {
"PropertyName": "User Name"
}
},
{
"errorCode": "NotEmpty",
"fieldName": "Password",
"message": "'Password' should not be empty.",
"meta": {
"PropertyName": "Password"
}
}
]
}
}
The tool here is a red-herring and you should be checking what data format the server endpoint is expecting its data in. Typically REST services are expecting requests as JSON, but that is not universally true.
So for example (including both header and body):
POST https://example.com/comments HTTP/1.1
content-type: application/json
{
"UserName": "myemail#address.com",
"Password": "My Password!",
"RememberMe": true
}
If you want to see what the server may be receiving, then you can check against a service such as https://requestbin.com/ - just don't include any sensitive data.

Docusign - send envelope REST API (POST multipart/form-data )

I'm trying to send an envelope in DocuSign using REST API. For adding the document to envelopes I'm using multipart/form-data POST method.
I tried sending this request using POSTMAN but I'm getting a below response:
{
"errorCode": "INVALID_CONTENT_TYPE",
"message": "Content Type specified is not supported. Content-Type for part[0] must be application/json or application/xml"
}
This is my POSTMAN request:
POST /restapi/v2/accounts/****/envelopes HTTP/1.1
Host: demo.docusign.net
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Authorization: Bearer *********
Cache-Control: no-cache
Postman-Token: c0b940e1-4b6c-4848-abd1-ed5c9c712cb5
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=""
{
"status": "sent",
"emailSubject": "Example of one recipient, type signer",
"documents": [{
"documentId": "1",
"name": "contract.pdf",
}],
"recipients": {
"signers": [{
"name": "Lisa Simpson",
"email": "lisa#email.com",
"recipientId": "1",
"routingOrder": "1",
"tabs": {
"signHereTabs": [{
"xPosition": "150",
"yPosition": "200",
"documentId": "1",
"pageNumber": "1"
}],
}
}]
}
}
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="Test.pdf"
Content-Type: application/pdf
------WebKitFormBoundary7MA4YWxkTrZu0gW--
My questions are:
Is there a way in POSTMAN to specify the Content-Type for part[0]?
What should be the key names for part[0] & part[1]?
How to pass documentid in part[1]?
I'm referring: https://docs.docusign.com/esign/restapi/Envelopes/Envelopes/create/#examples
REST API documentation
See below for a proper self-contained working DocuSign envelope using multi-part form vs multipart/form-data -
DocuSign Support Case 04093516 is closed and a Jira ticket was filed for the erroneous mention of form-data in the documentation about sending envelopes via REST API.
Hard returns and spacing are critical. Also, recommend you update email addresses to your test Gmail account, notice the same account with + can be used.
If using Postman make sure you are using "RAW" not form-data, x-www-form-urlencoded or binary. See image below:
Link here as well - https://blog.grigsbyconsultingllc.com/wp-content/uploads/Screenshot-2018-04-18-07.26.26.png
You still need headers, specifically content-type and authentication type aka :
-H 'content-type: multipart/form-data; boundary=AAA' \
-H 'x-docusign-authentication; See Stack Overflow link How should the header X-DocuSign-Authentication be used for REST and SOAP?
--AAA
Content-Type: application/json
Content-Disposition: form-data
{
"emailBlurb": "Test for CEFTAF Lab 2 Custom Fields Recipient Fields Document Fields",
"emailSubject": "Test for Dev 201 Lab 2",
"status": "created",
"notification":{
"useAccountDefaults":"false",
"reminders":{
"reminderEnabled":"true",
"reminderDelay":"2",
"reminderFrequency":"2"
},
"expirations":{
"expireEnabled":"true",
"expireAfter":"15",
"expireWarn":"1"
}
},
"compositeTemplates": [{
"inlineTemplates": [{
"sequence": "1",
"customFields": {
"textCustomFields": [
{
"fieldId": "123",
"name": "MYCustomID",
"show": "false",
"required": "false",
"value": "myId012345"
}
],
"listCustomFields": [
{
"listItems": [
"elementValue1","elementValue2","elementValue3"
],
"fieldId": "1234",
"name": "myArrayListofItems",
"show": "false",
"required": "false",
"value": "3"
}
]
},
"documents": [{
"documentId": "1",
"name": "test1.txt",
"documentFields": [
{
"name": "Test1",
"value": "value for test1"
}
],
},
{
"documentId": "2",
"name": "test2.txt"
},
{
"documentId": "3",
"name": "test3.txt"
}
],
"recipients": {
"carbonCopies": [
{
"email": "dsproservedemosoapui+Testcc#gmail.com",
"name": "David Grigsby (see all document)",
"recipientId": "3",
"routingOrder": "3"
},
{
"email": "dsproservedemosoapui+Testcc1#gmail.com",
"name": "David Grigsby (see all)",
"recipientId": "4",
"routingOrder": "4"
}
],
"signers": [{
"recipientId": "1",
"customFields": [
"Recip 1 ID 1234"
],
"name": "David Grigsby (Sees all)",
"email": "dsproservedemosoapui+Test1#gmail.com",
"routingOrder": "1",
"tabs": {
"signHereTabs": [{
"anchorString": "Sign1",
"tabLabel": "Sign Here 1"
}]
}
},
{
"recipientId": "2",
"name": "David Grigsby (sees all )",
"email": "david.grigsby#yahoo.com",
"routingOrder": "2",
"tabs": {
"signHereTabs": [{
"anchorString": "Sign2",
"tabLabel": "Sign Here 2"
}]
}
}
]
}
}]
}]
}
--AAA
Content-Type: application/txt
Content-Disposition: file; filename="test1.txt"; documentid=1
Test Document 1
Sign1 Here _______________________________ Custom1 Approve:
Sign2 Here _______________________________ Custom2 Approve:
--AAA
Content-Type: application/txt
Content-Disposition: file; filename="test2.txt"; documentid=2
Test Document 2
Sign1 Here _______________________________
--AAA
Content-Type: application/txt
Content-Disposition: file; filename="test3.txt"; documentid=3
Test Document 3
No Tabs for anyone means visbile to all by default unless excluded
--AAA--
And the difference for a PDF is below, recommend using Base64
--AAA
Content-Type: application/pdf
Content-Disposition: file; filename="f4506t.pdf"; documentid=1
Content-Transfer-Encoding: base64
JVBERi0xLjcNJeLjz9MNCjMwMSAwIG9iag08PC9MaW5lYXJpemVkIDEvTCA3NDAzMi9PIDMwMy9F
IDMzNjI2L04gMi9UIDczNjM4L0ggWyA2MzAgMjk2XT4+DWVuZG9iag0gICAgICAgICAgICAgICAg
.... pdf body bulk removed ......
o4IlmH0CxPYUYWBiYGBUB5PVDADOVQiaCmVuZHN0cmVhbQplbmRvYmoKc3RhcnR4cmVmCjg1MDUz
CiUlRU9GCg==
--AAA--
Image of Note from DocuSign Case:

DocuSign Request Signature by providing a pre-filled pdf document, while referencing the template id in DocuSign which defines the signature tab

I have a PDF document stored as Docusign Template that just defines a signature tab and no other information is filled in that PDF. From my application, I will be providing the same PDF with information filled in. Is it possible to request signature from my client providing the pre-filled PDF and reference the Docusign Template, so the signature tab shows up with the pre-filled data?
I am not sure if there is an API that supports this requirement. I looked at using composite templates, but it did not work as I expected, may be I was using it wrong. Here is the json request:
--BOUNDARY
Content-Type: application/json
Content-Disposition: form-data
--BOUNDARY
Content-Type: application/pdf
Content-Disposition: file; filename="form4506-doe.pdf"; documentId=1
{
"emailSubject": "Sent from a Template",
"templateRoles": [],
"status": "sent",
"compositeTemplates": [
{
"serverTemplates": [
{
"sequence": "1",
"templateId": "10ce17a0-0a25-4485-883c-72c1da059d13"
}
],
"inlineTemplates": [
{
"sequence": "1",
"recipients": {
"editors": [],
"agents": [],
"signers": [
{
"clientUserId": "1",
"recipientId": "1",
"name": "John Doe",
"email": "jdoe#example.com"
}
],
"certifiedDeliveries": [],
"carbonCopies": []
}
}
],
"document": {
"name": "form4506-doe.pdf",
"documentId": "1"
}
}
]
}
--BOUNDARY--
This request sent the pre-filled PDF to the client, but the signature tab is missing (which I expect it to have come from the template). Appreciate any help from DocuSign support.
I think I figured out the working combination. RoleName is required to be set on the Signer object, which shows the Signature tab on the merged template. Sequence needs to be re-ordered. Server template should be set to sequence 2 and inline template should be set to sequence 1. Document id should point to the document id from DocuSign template documents. Here is the working json request:
--BOUNDARY
Content-Type: application/json
Content-Disposition: form-data
{
"emailSubject": "Sent from a Template",
"templateRoles": [],
"status": "sent",
"compositeTemplates": [
{
"compositeTemplateId": "1",
"serverTemplates": [
{
"sequence": "2",
"templateId": "10ce17a0-0a25-4485-883c-72c1da059d13"
}
],
"inlineTemplates": [
{
"sequence": "1",
"recipients": {
"editors": [],
"agents": [],
"signers": [
{
"clientUserId": "1",
"recipientId": "1",
"name": "John Doe",
"email": "jdoe#example.com",
"roleName": "borrower"
}
],
"certifiedDeliveries": [],
"carbonCopies": []
},
"documents": [
{
"name": "form4506-doe.pdf",
"documentId": "98141843"
}
]
}
]
}
]}
--BOUNDARY
Content-Type: application/pdf
Content-Disposition: file; filename="form4506-doe.pdf"; documentId=98141843
<bytes of PDF removed>
--BOUNDARY--