Need Help on IMAP INBOX Search based on received date - imap

I am using a Open source IMAP C# library IMapX (http://hellowebapps.com/products/imapx/).
When I trying to get the emails from INBOX it is taking lot of time. Is there any way to Filter inbox based on received date?
The below code is a sample. The search is based on UNSEEN. I want to filter based on received date is Greater than given date.
ImapX.ImapClient client = new ImapX.ImapClient("imap.gmail.com", 993, true);
bool result = false;
result = client.Connection();
if (result)
MessageBox.Show("Connection Established");
result = client.LogIn(textBox1.Text, textBox2.Text);
if (result)
{
MessageBox.Show("Logged in");
ImapX.FolderCollection folders = client.Folders;
ImapX.MessageCollection messages = client.Folders["INBOX"].Search("UNSEEN", true); //true - means all message parts will be received from server
int unread = messages.Count;
string unseen = unread.ToString();
button1.Text = unseen;
}

You can use IMAP search data item SINCE. Example: "SINCE 18-Nov-2011".
Or if you interested in UNSEEN too then: "SINCE 18-Nov-2011 UNSEEN"

Related

Avoid Service invoked for too many times in one day Message in Google Sheet

I tried to get the redirect url in google sheet with the cache function to avoid the error message: Service invoked for too many times in one day. However, the following code return an error message, may i know how to fix it
function getRedirects(url) {
var params = {
'followRedirects': false,
'muteHttpExceptions': true
};
var followedUrls = [url];
var cache = CacheService.getScriptCache();
var properties = PropertiesService.getScriptProperties();
try {
let res = cache.get(url);
while (true) {
var res = UrlFetchApp.fetch(url, params);
if (res.getResponseCode() < 300 || res.getResponseCode() > 399) {
return followedUrls;
}
var url = res.getHeaders()['Location'];
followedUrls.push(url);
}
}
}
You are reaching Apps Script quota limit since there's a while-true
As per the documentation Quotas are set at different levels for users of consumer (such as gmail.com). Which in your case is URL Fetch calls - 20,000 / day
I'd change the while (true) line and foresee how many requests will be made beforehand. When you use var res = UrlFetchApp.fetch(url, params); a request / day is consumed so keep in mind that unless you own a Workspace Account you won't be able to change your quota limit.
Reference
Quotas for Google Services

How to apply deduplication for an array returned in Zapier Code output

I have a Zapier Code block that does fetch for JSON array and the preprocess this data. I cannot use Zapier Webhook with polling, because I need to process the data a bit.
Zapier Webhook offers deduplication feature, by having id parameter associated with the items returned in an array from the URL endpoint. How can I achieve the same for Zapier Code? Currently, my zap is trying to process and trigger on the same data twice. This leads to the error that Zapier tries to send out the same tweet twice, every time the Code is triggered.
Here is mock data returned by my Code:
output = [{id: 1, name: "foo"}, {id: 2, name: "bar"}]
Currently, without deduplication, I am getting this email and having my zap disabled:
Your Zap named XXX was just stopped. This happened because our systems detected this Zap posted a duplicate tweet, which is against Twitter's Terms Of Service.
You can use storage by Zapier to achieve this. the ideal flow will be :
Trigger
Storage by Zapier [Get Value (use storage key = lastItemId) ]
Code By Zapier (Filter array return only those record that has id greater than the lastItemId)
Storage By Zapier (Set Value) : update lastItemId with the last item processed by Code By Zapier step
You can also use StoreClient in place of the Storage By zapier, but always update a existing key lastItemId and compare id of the record with ```lastItemId`` and at the end update StoreCLient key (lastItemId)
Based on the answer from Kishor Patidar, here is my code. I am adding the example code, here is too some time to figure it out. Specifically, in my case, the items cannot be processed in the order of appearance (no running counter primary keys) and also there are some limitations how far in the future Zapier can schedule actions (you can delay only up to one month).
The store also has a limitation of 500 keys.
// We need store for deduplication
// https://zapier.com/help/create/code-webhooks/store-data-from-code-steps-with-storeclient
// https://www.uuidgenerator.net/
var store = StoreClient('xxx');
// Where do we get our JSON data
const url = "https://xxx";
// Call FB public backend to get scheduled battles
const resp = await fetch(url);
const data = await resp.json();
let processed = [];
for(let entry of data.entries) {
console.log("Processing entry", entry.id);
// Filter out events with a non-wanted prize type
if(entry.prizes[0].type != "mytype") {
continue;
}
// Zapier can only delay tweets for one month
// As the code fires every 30 minutes,
// we are only interested scheduling tweets that happen
// very soon
const when = Date.parse(entry.startDate);
const now = Date.now();
if(!when) {
throw new Error("startDate missing");
}
if(when > now + 24 * 3600 * 1000) {
// Milliseconds not going to happen for next 24h
console.log("Too soon to schedule", entry.id, entry.startDate, now);
continue;
} else {
console.log("Starting to schedule", entry.id, entry.startDate, now);
}
const key = "myprefix_" + entry.id;
// Do manual deduplication
// https://stackoverflow.com/questions/64893057/how-to-apply-deduplication-for-an-array-returned-in-zapier-code-output
const existing = await store.get(key);
if(existing) {
// Already processed
console.log("Entry already processed", entry.id);
continue;
}
// Calculate some parameters on entry based on nested arrays
// and such
entry.startTimeFormat = "HH:mm";
// Generate URL for the tweet
entry.signUpURL = `https://xxx/${entry.id}`;
processed.push(entry);
// Do not tweet this entry twice,
// by setting a marker flag for it in store
await store.set(key, "deduplicated");
}
output = processed;

Graph Api Delta token is not returning correct data

I am trying to use delta query to get the changes in one of the rooms calendars, when i use the start date and end date to set the initial request, it returns the correct events data and then afterwards when I use the delta token next time to make request, but it returns event data with tag saying this particular event has been deleted and does not return any valuable info apart form ID.
Here is my code
private async Task<IEventDeltaCollectionPage> GetEventData(GraphServiceClient graphClient, object deltaLink)
{
IEventDeltaCollectionPage page;
if (lastPage == null)
{
var queryOptions = new List<QueryOption>();
if (deltaLink == null)
{
queryOptions = new List<QueryOption>()
{
new QueryOption("startdatetime", "2020-01-16T00:00:00Z"),
new QueryOption("enddatetime", "2020-01-24T00:00:00Z")
};
}
else
{
queryOptions = new List<QueryOption>()
{
new QueryOption("$deltatoken", deltaLink.ToString())
};
}
page = await graphClient
.Users["nitroom2#domain.onmicrosoft.com"].CalendarView
.Delta()
.Request(queryOptions)
.GetAsync();
}
else
{
lastPage.InitializeNextPageRequest(graphClient, deltaLink.ToString());
page = await lastPage.NextPageRequest.GetAsync();
}
lastPage = page;
return page;
}
AS you can see this code will either look for dates range or delta token. so what I do is I initially make a call without a delta token, then once I get the final response I get the delta token. I restart the application this time and I provide the hard-coded delta token. Before restarting the application I also make sure that there is either a new event created or updated in the rooms calendar and then I restart the application with the delta token. I get a response back with some event data but that's telling me the event has been deleted, but that's not true.
Not sure what i am misisng here. can any abody suggest?
when using delta query Microsoft Graph returns as deleted new/updated/deleted items that are not in start-end date range of the initial request.
please check if that was your case :)

HTPP POST to Google Forms or Alternative

I have a google form setup that emails me upon a manual submission when somebody fills it out (new lead) and transfers the information to a Google spreadsheet. Easy enough to figure that out.
However, now I'm trying to figure out how to send the same information information contained within a url string and automatically POST that information to the form. Or find a company who offers that ability, via an api or other means. So far I've tested out jotform and a few others. The information passed along fine, but it doesn't auto populate the fields. I assume it's because it doesn't know that x=y due to the fields being named differently. I've found a ton of documentation about pre-populating the forms, but not much about filling out a form every time a new POST url is generated.
URL looks like the following
VARhttps://script.google.com/macros/s/XXXXXXXXXXXXXXXX/exec?/--A--
first_name--B--/--A--last_name--B--/--A--address1--B--/--A--city--B--/--A--
state--B--/--A--postal_code--B--/--A--phone_number--B--/--A--date_of_birth--
B--/--A--email--B--
Information passed is as follows
https://website
here.com/Pamela/Urne/123+Test+Street/Henderson/TX/75652/281XXXXXX/1974-01-
01/test0101cw#test.com
The script I'm testing out
// original from: http://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/
// original gist: https://gist.github.com/willpatera/ee41ae374d3c9839c2d6
function doGet(e){
return handleResponse(e);
}
// Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
I get a success message after accessing the url, but all information listed in the spreadsheet is "Undefined."
That's as far as I got so far. If somebody knows an easier solution or can point me in the right direction I'd appreciate it.

DotNetOpenAuth detect fetch request like google

With google, you can fetch the user's email like this:
var fetch = new FetchRequest();
fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
request.AddExtension(fetch);
and get it back like this:
var fetch = response.GetExtension<FetchResponse>();
string email = "";
if (fetch != null)
{
email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
}
When writing a provider, how can I return the values asked for?
The OpenIdProviderWebForms sample that comes with DotNetOpenAuth includes returning user attributes. Have you checked it out?

Resources