I am using the Gmail API for Android for an application to send emails.
I want to send the mails such that they are received in the Social group of messages.
So is it possible in any way that I can set the labels for an email while sending it using the Gmail API ?
It is possible for us to set labels while sending mails through mail.google.com so how can the same be achieved with the Gmail API ?
You cannot specify the labels message should have when sending it. Under what tab certain messages should end up under is up to the user.
But if you are sending a message to the user himself howewer, it's not that hard to modify the message once it has been sent. When you send a message, you get all the label that were applied to the message in the response. Just send a message, and then modify the labels, and you are done.
Here's an example (with regular http-requests, but you could do the same with one of the client libraries):
// Base64-encoding the message and making it url-safe by replacing
// all '+' with '-', and all '/' with '_'.
btoa("To: example#gmail.com\n" +
"From: example#gmail.com\n" +
"Subject: Cool man\n\n" +
"Here is the message").replace(/\+/g, '-').replace(/\//g, '_');
// => "VG86IGV4YW1wbGVAZ21haWwuY29tCkZyb206IGV4YW1wbGVAZ21haWwuY29tClN1YmplY3Q6IFRoaXMgaXMgdGhlIHN1YmplY3QKCkhlcmUgaXMgd2VyZSB0aGUgbWVzc2FnZSBnb2Vz"
Sending the message:
POST https://www.googleapis.com/gmail/v1/users/me/messages/send
{
"raw": "VG86IGV4YW1wbGVAZ21haWwuY29tCkZyb206IGV4YW1wbGVAZ21haWwuY29tClN1YmplY3Q6IFRoaXMgaXMgdGhlIHN1YmplY3QKCkhlcmUgaXMgd2VyZSB0aGUgbWVzc2FnZSBnb2Vz"
}
Response
{
"id": "150866b2f6956617",
"threadId": "150866b2f6956617",
"labelIds": [
"SENT",
"INBOX",
"UNREAD"
]
}
Then, I just the add the CATEGORY_SOCIAL-label to get it to show under the social-tab (removing the INBOX-label will not show it at all).
Request
POST https://www.googleapis.com/gmail/v1/users/me/messages/150866b2f6956617/modify
{
"addLabelIds": [
"CATEGORY_SOCIAL"
]
}
Worked great!
Related
I am sending data-message to my android application via FCM.But when I change the data payload structure,it does not seem to affect.
The FCM payload is
{
"to" : "eF3lccIdYs4:APA91bHpC1xWNl4MZXXXX",
"data" : {
"caller_name" : "Sobin Thomas",
"room" : "2000",
"call_type" : "audio"
},
"time_to_live" : 0
}
If I change it to
{
"to" : "eF3lccIdYs4:APA91bHpC1xWNl4MZXXXX",
"data" : {
"**caller**" : "Sobin Thomas",
"**room_number**" : "2000",
"call_type" : "audio",
**"call_time" : "2018-04-24 12:12:12",**
},
"time_to_live" : 0
}
Old data payload is still getting in the mobile app. And of course the data payload values change
Firebase Cloud Messaging will try to deliver every message, not just the last one. What's likely happening is that your device is receiving multiple messages in short succession, and only displays one.
If you want new messages to replace older message, you'll need to specify a so-called collapse_key. From the documentation:
This parameter identifies a group of messages (e.g., with collapse_key: "Updates Available") that can be collapsed, so that only the last message gets sent when delivery can be resumed. This is intended to avoid sending too many of the same messages when the device comes back online or becomes active.
Based on the documentation, it is my understanding that there are two types of messages that Firebase can send: Notification and Data. Also, they can be either collapsible or non-collapsible with non-collapsible being the default for data messages. This would mean that each message is delivered to the client app. See below:
However, when I send data messages to my client they are collapsed. For example, I send one and it appears in the notification bar with no problem but if I don't open it and another message comes in, it is replaced by the new message. Here's some of my code.
Data message:
//create the notification payload
let payload = {
data: {
title: 'Title',
context: context,
parent: parent,
body: user + " commented on your contribution.",
sound: 'default'
}
};
//send the notification
return admin.messaging().sendToDevice(userToken, payload).then(ok =>{
console.log('Notification sent to: ' + submitter);
}).catch(error => {
console.log('Could not send notification.');
});
What am I doing wrong? I want each notification to appear and not be replaced.
You are debugging at the wrong end. The actual problem is on the client side where you are posting the notification.
While posting the notification if the notification id is the same Android OS will replace the existing notification.
Look for the notify() in your code. Refer to this doc for more details : https://developer.android.com/reference/android/app/NotificationManager.html#notify(int, android.app.Notification)
We are using Firebase in a SIP app to send us missed call notifications and chat notifications whenever the app was offline.
While sending and receiving works fine, we have the effect on the Android client, that 5 missed calls obv produce 5 missed-call-notifications, filling up the notification bar on the client device.
How can we merge those notifications together, to just show a single "5 missed calls" notification?
Is there any additional flag (like grouping) we can put in the data or notification part of the message?
Here is an example of our current missed call notification:
{
"to":"<<FCMToken>>",
"priority":"high",
"notification":{
"title":"<<Displayname-of-Caller>>",
"text":"<<Date-and-time-of-call>>",
"icon":"icon_notification_missed",
"click_action":"MISSED_CALL"
},
"data":{
"type":"sip-call-missed"
}
}
So what's the trick in combining them together as one?
We found the correct solution.
There are more existing keywords for the notification content.
The one we needed was "tag".
We can even localize the client-side text of the notification by supplying a resource name in loc keys.
Here is a correct message that can be bundled together:
{
"to":"<<FCMToken>>",
"priority":"high",
"notification":{
"title_loc_key":"notification_missed_call",
"tag":"MISSED_CALL",
"body_loc_key":"notification_missed_call_multiple",
"body_loc_args":["<<missed_call_count>>"],
"icon":"icon_nav_main_chat",
"click_action":"MISSED_CALL"
},
"data":{
"type":"sip-call-missed"
}
}
The tag will be merged by the client ... say: they will replace each other. Whenever a notification with a tag arrives, it replaces all other existing notifications with the same tag.
So the trick here is, to supply a running count <<missed_call_count>> (which the server has to count), so the client can show an increasing number, like "5 missed calls".
The string "%d missed calls" is stored in the client side string resource named "notification_missed_call_multiple".
To send a message from FCM backend, we have this view :
I wanna to get the message label (libellé du message) from RemoteMessage. When I debug for the field, the content in the message is labeled as google.c.a.c_l, which I think is an internal field.
First, I just wonder the same as your question. But after read the document here and played around with it, I found that:
You cannot get the message label on client device, because it is just a label for display on firebase console only.
To get title at client side, you have to use Advanced options which is auto collapse at the bottom. With Advanced options, you can also send a data payload to the client by key/value.
Then remoteMessage.getNotification().getBody() for notification's message body (from Message text/Texte du message), remoteMessage.getNotification().getTitle() for notitifcation's title (from Advanced options), remoteMessage.getData() for data payload (from Advanced options).
Try to get it with remoteMessage.getNotification().getTitle(). However, check before if remoteMessage.getNotification() != null.
Hope this helps.
Can anyone please help me with the sample code for google push notifications. I am getting an error in json message.
Here is the code:
local googleApiKey = "**********************"
local googleRegistrationId = nil
-- Called when a sent notification has succeeded or failed.
local function onSendNotification(event)
local errorMessage = nil
-- Determine if we have successfully sent the notification to Google's server.
if event.isError then
-- Failed to connect to the server.
-- This typically happens due to lack of Internet access.
errorMessage = "Failed to connect to the server."
elseif event.status == 200 then
-- A status code of 200 means that the notification was sent succcessfully.
print("Notification was sent successfully.")
elseif event.status == 400 then
-- There was an error in the sent notification's JSON data.
errorMessage = event.response
elseif event.status == 401 then
-- There was a user authentication error.
errorMessage = "Failed to authenticate the sender's Google Play account."
elseif (event.status >= 500) and (event.status <= 599) then
-- The Google Cloud Messaging server failed to process the given notification.
-- This indicates an internal error on the server side or the server is temporarily unavailable.
-- In this case, we are supposed to silently fail and try again later.
errorMessage = "Server failed to process the request. Please try again later."
end
-- Display an error message if there was a failure.
if errorMessage then
native.showAlert("Notification Error", errorMessage, { "OK" })
end
end
-- Sends the given JSON message to the Google Cloud Messaging server to be pushed to Android devices.
local function sendNotification(jsonMessage)
-- Do not continue if a Google API Key was not provided.
if not googleApiKey then
return
end
-- Print the JSON message to the log.
print("--- Sending Notification ----")
print(jsonMessage)
-- Send the push notification to this app.
local url = "**************************"
local parameters =
{
headers =
{
["Authorization"] = "key=" .. googleApiKey,
["Content-Type"] = "application/json",
},
body = jsonMessage,
}
network.request(url, "POST", onSendNotification, parameters)
end
-- Sends a push notification when the screen has been tapped.
local function onTap(event)
-- Do not continue if this app has not been registered for push notifications yet.
if not googleRegistrationId then
return
end
-- Set up a JSON message to send a push notification to this app.
-- The "registration_ids" tells Google to whom this push notification should be delivered to.
-- The "alert" field sets the message to be displayed when the notification has been received.
-- The "sound" field is optional and will play a sound file in the app's ResourceDirectory.
-- The "custom" field is optional and will be delivered by the notification event's "event.custom" property.
local jsonMessage =
[[
{
"registration_ids": ["]] .. tostring(googleRegistrationId) .. [["],
"data":
{
"alert": "Hello World!",
"sound": "notification.wav",
"custom":
{
"boolean": true,
"number": 123.456,
"string": "Custom data test.",
"array": [ true, false, 0, 1, "", "This is a test." ],
"table": { "x": 1, "y": 2 }
}
}
}
]]
sendNotification(jsonMessage)
end
Runtime:addEventListener("tap", onTap)
-- Prints all contents of a Lua table to the log.
local function printTable(table, stringPrefix)
if not stringPrefix then
stringPrefix = "### "
end
if type(table) == "table" then
for key, value in pairs(table) do
if type(value) == "table" then
print(stringPrefix .. tostring(key))
print(stringPrefix .. "{")
printTable(value, stringPrefix .. " ")
print(stringPrefix .. "}")
else
print(stringPrefix .. tostring(key) .. ": " .. tostring(value))
end
end
end
end
-- Called when a notification event has been received.
local function onNotification(event)
if event.type == "remoteRegistration" then
-- This device has just been registered for Google Cloud Messaging (GCM) push notifications.
-- Store the Registration ID that was assigned to this application by Google.
googleRegistrationId = event.token
-- Display a message indicating that registration was successful.
local message = "This app has successfully registered for Google push notifications."
native.showAlert("Information", message, { "OK" })
-- Print the registration event to the log.
print("### --- Registration Event ---")
printTable(event)
else
-- A push notification has just been received. Print it to the log.
print("### --- Notification Event ---")
printTable(event)
end
end
-- Set up a notification listener.
Runtime:addEventListener("notification", onNotification)
-- Print this app's launch arguments to the log.
-- This allows you to view what these arguments provide when this app is started by tapping a notification.
local launchArgs = ...
print("### --- Launch Arguments ---")
printTable(launchArgs)
Whenever this code is called and Error 400 notification appears. Is there a way to send custom push notifications to android device using corona?
Json is completely fine. There might be the problem of url you set up and for triangle notification problem you can go through the following link:
http://jsonlint.com/#