download only the new content in email reply by google gmail api - rest

I am trying to access Gmail messages via google API.
https://developers.google.com/gmail/api/v1/reference/users/threads
But the payload field returns the base64 of the body of the email. When an email is in a thread, it is usually to reply to a previous email. Therefore only the reply part is useful to show. The reply part can be shown by the GUI interface. Is there a way to get only the reply part via the API?

Unfortunately, there's no direct method of obtaining the last reply for each thread.
If you want to retrieve the last reply of the email threads you should first of all retrieve all the messages by using a GET request like this:
GET https://www.googleapis.com/gmail/v1/users/userId/messages
The request response will look something like this:
{
"messages": [
users.messages Resource
],
"nextPageToken": string,
"resultSizeEstimate": unsigned integer
}
Where the users.messages Resource looks something like this:
{
"id": "",
"threadId": ""
}
Having the list of all the users.messages Resources, the ones which contain the same threadId are the emails which in fact contain replies.
So in order to obtain the last reply, you could find which threadIds appear more than once, and then retrieve the last occurrence of it as it is the last reply. Or if you want all the replies (apart from the original email), you can retrieve all the occurrences apart from the first one (which is represented by the original email).
Lastly, to retrieve the message you can use a GET request like this:
GET https://www.googleapis.com/gmail/v1/users/userId/messages/id
Note: The userId is represented by the email address from which you want to retrieve the emails/replies and the id is represented by the id of the message.
Reference
Users.threads: list;
Users.threads: get;
Users.messages: list;
Users.messages: get.

Related

Invalid JSON message received

I'm trying to POST into an API I have made, and I am testing it using Postman. I am getting back a 400 Bad Request error back as a response with the message Invalid JSON message received.
This is an example of the record being feedback to the user using GET.
{
"id":3,
"title":"Radio Etiquette Book",
"summary":"This book provides advice on how to present a radio programme with flair.",
"timestamp":"2016-12-22T18:18:20+0000",
"author":{"id":1,...***},
"reviews":
}
I presume the problem is with author because author contains sub fields, such as ID, username, password and sub classes called entries (books created by that author), and reviews (reviews written by that author).
How can I POST a new entry to avoid a 400 Bad Request error? I'm not sure which value it is, that I am posting incorrectly, but debating on whether it is actually author, and how it should be entered.
You can use a site like JSONLint to inspect whether or not the JSON you're trying to send is properly formatted. It should be able to show you the line of the error and why it might not match the JSON spec.
link to JSONLint

Mailgun API: Batch Sending vs. Individual Calls

Background
We're building an application that will process & send emails via Mailgun. These are sometimes one-off messages, initiated by a transaction. Some emails, though, will be sent to 30k+ at once.
Eg, a newsletter to all members.
Considerations
Mailgun offers a Batch Sending option with their API. Using "Recipient Variables", you can include dynamic values that are paired with a particular user.
This Batch Sending functionality is limited, however. You cannot send more than 1,000 recipients per request, which means we have to iterate through a recipient list (on our database) for each set of 1,000. Mailgun provides an example of how this might work, using Python (scroll about 2/3 down).
Question
Are there any advantages to batch sending (ie, sending an email to a group of recipients through a single API call, using recipient variables) as opposed to making our own loop, variable substitutions and individual API calls?
I assume this is more taxing on our server, as it would be processing each message itself, instead of just offloading all that data to Mailgun's server for heavy-lifting on their end. But I also like the flexibility & simplicity of handling that on our end and sending a "fully-rendered" message to Mailgun, one at a time, without having to iterate 1k at a time.
Any thoughts on best practices, or considerations we should take into account?
Stumbled onto this today, and felt it provided a pretty good summary/answer for my original question. I wanted to post this as an answer, in case anybody else has this question and hasn't found this Mailgun post. Straight from the horse's mouth, too. The nutshell version:
For PHP, at least, the SDK has a Mailgun class, with a BatchMessage() method. This actually handles the counting of recipients for you, so you can just queue up as many email addresses as you want (ie, more than 1k) and Mailgun will fire off to the API endpoint as needed. Pretty slick!
Here's their original wording, plus a link to the page.
Sending a message with Mailgun PHP SDK + Batch Message:
Batch Message
In addition to Message Builder, we have Batch Message. This class
allows you to build a message and submit a template message in
batches, up to 1,000 recipients per post. The benefit of using this
class is that the recipients tally is monitored and will automatically
submit the message to the endpoint when you've added the 1,000th
recipient. This means you can build your message and begin iterating
through your database. Forget about sending the message, the SDK will
keep track of posting to the API when necessary.
// First, instantiate the SDK with your API credentials and define your domain.
$mgClient = new Mailgun("key-example");
$domain = "example.com";
// Next, instantiate a Message Builder object from the SDK, pass in your sending domain.
$batchMsg = $mgClient->BatchMessage($domain);
// Define the from address.
$batchMsg->setFromAddress("dwight#example.com",
array("first"=>"Dwight", "last" => "Schrute"));
// Define the subject.
$batchMsg->setSubject("Help!");
// Define the body of the message.
$batchMsg->setTextBody("The printer is on fire!");
// Next, let's add a few recipients to the batch job.
$batchMsg->addToRecipient("pam#example.com",
array("first" => "pam", "last" => "Beesly"));
$batchMsg->addToRecipient("jim#example.com",
array("first" => "Jim", "last" => "Halpert"));
$batchMsg->addToRecipient("andy#example.com",
array("first" => "Andy", "last" => "Bernard"));
// ...etc...etc...
// After 1,000 recipeints,
// Batch Message will automatically post your message to the messages endpoint.
// Call finalize() to send any remaining recipients still in the buffer.
$batchMsg->finalize();
The answer of #cdwyer and #nikoshr is very helpful, but bit legacy. Used methods in the example are deprecated. Here is current usage of lib:
$batchMessage = $this->mailgun->messages()->getBatchMessage('mydomain.com');
$batchMessage->setFromAddress('user#domain.com');
$batchMessage->setReplyToAddress('user2#domain.com');
$batchMessage->setSubject('Contact form | Company');
$batchMessage->setHtmlBody('<html>...</html>');
foreach ($recipients as $recipient) {
$batchMessage->addToRecipient($recipient);
}
$batchMessage->finalize();
More info at documentation.

How to get the ItemId of save-to-sent copy when sending mail via EWS

The EWS documentation says that to send a message and save a copy to the Sent Items folder, you should use the CreateItem operation with a MessageDisposition value of SendAndSaveCopy.
<m:CreateItem MessageDisposition="SendAndSaveCopy">
<m:SavedItemFolderId>
<t:DistinguishedFolderId Id="sentitems" />
</m:SavedItemFolderId>
<m:Items>
<t:Message>
<t:Subject>Company Soccer Team</t:Subject>
<t:Body BodyType="HTML">Are you interested in joining?</t:Body>
<t:ToRecipients>
<t:Mailbox>
<t:EmailAddress>sadie#contoso.com </t:EmailAddress>
</t:Mailbox>
</t:ToRecipients>
</t:Message>
</m:Items>
</m:CreateItem>
On success, "the server responds to the CreateItem request with a CreateItemResponse message that includes a ResponseCode value of NoError, which indicates that the email was created successfully, and the ItemId of the newly created message."
Using EWS against Office 365, this works almost successfully. The message is sent, the copy is saved to Sent Items... but the ItemId of the saved copy is not returned in the response:
<m:CreateItemResponse>
<m:ResponseMessages>
<m:CreateItemResponseMessage ResponseClass="Success">
<m:ResponseCode>NoError</m:ResponseCode>
<m:Items />
</m:CreateItemResponseMessage>
</m:ResponseMessages>
</m:CreateItemResponse>
Is there a way to direct the EWS server to actually return the ItemId of the saved copy? Alternatively, what's the preferred mechanism for locating the saved copy once the send completes?
Evidently the documentation is either wrong or inapplicable. This MSDN blog post matches my experience: no ItemId is returned from a SendAndSaveCopy CreateItem request. It suggests the following:
Simply stamp your e-mail message with a custom extended property when you create the message, and then use that extended property to find the message in the Sent Items folder after it has been sent.
A commenter suggests that rather than using an expensive FindItems-with-SearchFilter call to locate the custom-property-stamped saved copy, you should instead do the following:
1. Set your extended prop.
2. Do a FindItem with NO restriction against the sent items folder, SORTED by creation date descending with a indexed page view of about 5. Include your extended prop in the PropertySet.
3. Iterate across the results looking for your extended prop.

Set "reply-to" header field for mailgun

Is it possible to set the "reply-to" header field in a Mailgun list? While conversations are sometimes nice, people are getting annoyed at the volume of mail from one particular list, in which respondents ignore the instruction to send the message to a certain email address and hit reply, resulting in dozens (or more) messages containing things like "Got it!" or "I'm coming!" when only one person needs to see the response.
For this particular list, the ideal situation would be to limit the allowed senders to just a few people, but as none of them use services quite as nice as Gmail or a standalone email client (additional SMTP logins cannot be established), I've not found any way to limit the inanity. Does anyone know how to do this?
I am not sure if you are still looking for the answer, but you can set the Reply-To header using the API.
h:Reply-To
I have been using it with an email hash - each user gets a unique hash in the reply-to field so I know who is replying. Basically the reply-to looks like this:
"h:Reply-To" : "inboundaddress+hash#mydomain.com"
In the routes panel add the following and you can redirect to your email or to an HTTP endpoint:
match_recipient("^inboundaddress\+(.*)#mydomain.com")
Hope that helps.
Justin
You can programmatically add the header "Reply-To" in the data you are sending.
For example, this snippet works well in Python:
import requests
url = 'https://api.mailgun.net/v3/YOUR_ACCOUNT/messages'
auth = ('api', 'YOUR_KEY')
data = {
'from': 'Info <info#email.com>',
'to': ['user1#email.com', 'user2#email.com'],
'subject': 'test email',
'html': '<b>hello!</b> that's all.,
'text': 'plain text here',
'o:tag': ['categoria 1', 'categoria 2']
}
data['h:Reply-To']="My name <my#email.com>" # <------------- HERE!
res = requests.post(url, auth=auth, data=data)
Please check this issue in mailgun-js
https://github.com/bojand/mailgun-js/issues/57
You just need to add 'h:Reply-To' to your email configuration object:
const options = {from, to, subject, text, html};
if(replyToAddress){
options['h:Reply-To'] = replyToAddress;
}
That will add new header to the e-mail :)
I have been looking for the exact same functionality and have not yet found one. I even tried using the Routes but that did nothing more than forward an email before sending it out to everyone else. I opened a ticket with support and received the same reply. There is not a way to set that at this time.

Modelling REST with hierarchy

How would one model resources that are hierarchical? Assume for example that a person has a "message board" and that a "message" is a resource. Let's say that the "message" can have replies so that it forms a discussion thread. How does one model the notion of a thread?
Does the "message" include it's children? Is the "thread" it's own resource? Finally, what kind of REST URI would work in this instance?
If you consider that all replies to a message are also messages I would give an id to every one of them and use these URIs:
#message {id} (only the message, no replies)
/messages/{id}
#replies to the {id} message (a list of the id's of the replies)
/messages/{id}/replies
To create a new message do a post to the uri
/messages
To create a reply to a message {id} do a post to
/messages/{id}/replies
Update
I will modify here my previous answer. Hopefully this time in a correct Restful style.
You have an entry point uri, let's call it {messages}.
GET {messages} -> list of uris of all the messages, {message1}, {message2}, etc.
GET {message1} -> responds with the message1 document, for example in xml it could be:
<message responses="{link to message1 responses}">
<date>...</date>
<body>...</body>
</message>
{link to message1 responses} is the link that the client has to follow to get the list of uris of the responses.
If a message is a response to another it will include that in his content, for example
<message responses="{link to message1 responses}" inResponseTo="{uri}" >
<date>...</date>
<body>...</body>
</message>
Now to add new messages just post it to the original {messages} uri. If the message is a response to other message just include it in its content (note that this is an efective change to the inital answer where you post the replies to an special uri).
To modify some message do a PUT to its uri.
All the uris coudl follow thats of the first part of the answer, but this is not necessary.
So far every response has not been RESTful at all. REST doesn't need to be hierarchical. Just have an entry point like /threads/ which gives full URIs of each thread resource, and each thread resource would respond with the URIs of each message in itself, or the top message plus the URIs of its replies, and so on. The way these URIs are generated is immaterial as long as they are discoverable via hypertext from an entry point.