How to implement Microsoft Graph deferred sending - email

I am trying to implement a deferred sending function to my site which currently sends email via Microsoft Graph. I have found some articles about SingleValueLegacyExtendedProperty being used to defer sending, but so far has been unsuccessful with it.
My current code just ignores the deferred sending time and sends the email immediately.
var message = new Message
{
Subject = Subject,
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = bodyText
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = recipient
}
}
},
};
message.SingleValueExtendedProperties = new MessageSingleValueExtendedPropertiesCollectionPage
{
new SingleValueLegacyExtendedProperty()
{
Id = "SystemTime 0x3FEF",
Value = DateTimeToSend.ToString("o")
}
};
var saveToSentItems = true;
await graphServiceClient.Me
.SendMail(message, saveToSentItems)
.Request()
.PostAsync();
In this article they suggest that the ID should be String {8ECCC264-6880-4EBE-992F-8888D2EEAA1D} Name pidTagDeferredSendTime when passing as JSON but it looks like that was not successful for other. I checked and can confirm that it did not work for me either.

Its important that the DateTime that you want the message to be sent is in UTC eg
"value": "2022-08-01T23:39:00Z"
Using local time won't work as Exchange does everything in UTC

Related

I want to trigger mail when the bot says that it has no answer

I want to trigger mail when the bot says that it has no answer.
I'm using MS bot framework SDk4, and using LUIS and QnA maker also, when the bot reached the to a point where it says that it has no answer , we want a mail to be triggered or add a new item in the sharepoint
If you want to add a no answer to a SharePoint List, I managed to get it working using the csom-node package and Bot Framework v4 / NodeJS. Granted, it's not the most elegant solution, but it works.
Bot.JS
const csomapi = require('../node_modules/csom-node');
settings = require('../settings').settings;
// Set CSOM settings
csomapi.setLoaderOptions({url: settings.siteurl});
Bit further down the page...
// If no answers were returned from QnA Maker, reply with help.
} else {
await context.sendActivity("Er sorry, I don't seem to have an answer.");
console.log(context.activity.text);
var response = context.activity.text;
var authCtx = new AuthenticationContext(settings.siteurl);
authCtx.acquireTokenForApp(settings.clientId, settings.clientSecret, function (err, data) {
var ctx = new SP.ClientContext("/sites/yoursite"); //set root web
authCtx.setAuthenticationCookie(ctx); //authenticate
var web = ctx.get_web();
var list = web.get_lists().getByTitle('YourList');
var creationInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(creationInfo);
listItem.set_item('Title', response);
listItem.update();
ctx.load(listItem);
ctx.executeQueryAsync();
});
}
Proactive Messaging doesn't really work for email (to prevent spam), so you're better off not using the Bot Framework SDK for the email portion. #Baruch's link, How to send email in ASP.NET C# is good if you're using the C# SDK. Here's one for sending emails in Node.
All you have to do is send the email when QnA Maker doesn't return any results. In this sample, you would do so here:
if (response != null && response.Length > 0)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response[0].Answer), cancellationToken);
}
else
{
await turnContext.SendActivityAsync(MessageFactory.Text("No QnA Maker answers were found."), cancellationToken);
// Add code that sends Notification Email
}
That being said, if you'd like to try a semi-proactive route, you can enable the Email Channel in your bot, then use this:
if (response != null && response.Length > 0)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response[0].Answer), cancellationToken);
}
else
{
await turnContext.SendActivityAsync(MessageFactory.Text("No QnA Maker answers were found."), cancellationToken);
MicrosoftAppCredentials.TrustServiceUrl(#"https://email.botframework.com/", DateTime.MaxValue);
var user = new ChannelAccount(name: "MyUser", id: "<notified Email Address>");
var parameters = new ConversationParameters()
{
Members = new ChannelAccount[] { user },
Bot = turnContext.Activity.Recipient
};
var connector = new ConnectorClient(new Uri("https://email.botframework.com"), "<appId>", "<appPassword>");
var conversation = await connector.Conversations.CreateConversationAsync(parameters);
var activity = MessageFactory.Text("This is a notification email");
activity.From = parameters.Bot;
activity.Recipient = user;
await connector.Conversations.SendToConversationAsync(conversation.Id, activity);
}
The catch is that <notified Email Address> has to send a message to the bot before any notifications will work. If it doesn't, it will return a 401: Unauthorized error. Again, I don't recommend this route.
Note: If you're using the Dispatch sample, you'd place the code here:
private async Task ProcessSampleQnAAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
_logger.LogInformation("ProcessSampleQnAAsync");
var results = await _botServices.SampleQnA.GetAnswersAsync(turnContext);
if (results.Any())
{
await turnContext.SendActivityAsync(MessageFactory.Text(results.First().Answer), cancellationToken);
}
else
{
// PLACE IT HERE
await turnContext.SendActivityAsync(MessageFactory.Text("Sorry, could not find an answer in the Q and A system."), cancellationToken);
}
}

xamarin forms: Calling phone and sending email (IOS, Android and UWP)

Currently using following code for calling and email features, but it is only working in Android and not working in IOS. Also, I need these features in UWP.
For call:
string phoneno = "1234567890";
Device.OpenUri(new Uri("tel:" + phoneno));
For mail:
string email = "sreejithsree139#gmail.com";
Device.OpenUri(new Uri("mailto:" + email ));
Any package available for this?
Xamarin.Essentials (Nuget) is available as a preview package and contains functionality to both open the default mail app and attach information such as the recipients, subject and the body as well as open the phone dialer with a certain number.
There is also a blog post about Xamarin.Essentials available on blog.xamarin.com.
Edit:
As for your mail issue, Xamarin.Essentials expects an array of strings as recipients so you are able to send mail to multiple people at once. Just pass a string array with one single value.
var recipients = new string[1] {"me#watercod.es"};
If you're using the overload that expects an EmailMessage instance, you are supposed to pass a List of string objects.
In that case, the following should work:
var recipients = new List<string> {"me#watercod.es"};
Updating the complete code for calling and mailing features using Xamarin.Essentials, this might help others.
For call:
try
{
PhoneDialer.Open(number);
}
catch (ArgumentNullException anEx)
{
// Number was null or white space
}
catch (FeatureNotSupportedException ex)
{
// Phone Dialer is not supported on this device.
}
catch (Exception ex)
{
// Other error has occurred.
}
For Mail:
List<string> recipients = new List<string>();
string useremail = email.Text;
recipients.Add(useremail);
try
{
var message = new EmailMessage
{
//Subject = subject,
//Body = body,
To = recipients
//Cc = ccRecipients,
//Bcc = bccRecipients
};
await Email.ComposeAsync(message);
}
catch (Exception ex)
{
Debug.WriteLine("Exception:>>"+ex);
}
Hello to make a call in UWP:
if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.ApplicationModel.Calls.PhoneCallManager"))
{
Windows.ApplicationModel.Calls.PhoneCallManager.ShowPhoneCallUI("123", "name to call");
}
To send a Text:
private async void ComposeSms(Windows.ApplicationModel.Contacts.Contact recipient,
string messageBody,
StorageFile attachmentFile,
string mimeType)
{
var chatMessage = new Windows.ApplicationModel.Chat.ChatMessage();
chatMessage.Body = messageBody;
if (attachmentFile != null)
{
var stream = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(attachmentFile);
var attachment = new Windows.ApplicationModel.Chat.ChatMessageAttachment(
mimeType,
stream);
chatMessage.Attachments.Add(attachment);
}
var phone = recipient.Phones.FirstOrDefault<Windows.ApplicationModel.Contacts.ContactPhone>();
if (phone != null)
{
chatMessage.Recipients.Add(phone.Number);
}
await Windows.ApplicationModel.Chat.ChatMessageManager.ShowComposeSmsMessageAsync(chatMessage);
}
as found in Microsoft documentation here: Compose SMS documentation
==> So you can make (If not already done) a shared service interface in your Xamarin app, then the implementation with these codes in your UWP app...
To send an email:
To send an email in UWP, you can refer to the Microsoft documentation too:
Send Email documentation (UWP)
Using a plugin
Else you can use a Xamarin plugin:
documentation: Xamarin cross messaging plugin
Nuget: Nuget plugin package
In our app, we are doing the phone calling with a DependencyService.
Therefore in our PCL, we have
public interface IPhoneCall
{
void Call(string number);
}
On the iOS side, the following method does the calling:
public void Call(string number)
{
if (string.IsNullOrEmpty(number))
return;
var url = new NSUrl("tel:" + number);
if (!UIApplication.SharedApplication.OpenUrl(url))
{
var av = new UIAlertView("Error",
"Your device does not support calls",
null,
Keys.Messages.BUTTON_OK,
null);
av.Show();
}
}
If don't want to wait for the Xamarin essentials that is still in pre-release as of today, you can use this open source plugin. It works on iOS, Android and UWP. There is a sample from the github documentation :
// Make Phone Call
var phoneDialer = CrossMessaging.Current.PhoneDialer;
if (phoneDialer.CanMakePhoneCall)
phoneDialer.MakePhoneCall("+27219333000");
// Send Sms
var smsMessenger = CrossMessaging.Current.SmsMessenger;
if (smsMessenger.CanSendSms)
smsMessenger.SendSms("+27213894839493", "Well hello there from Xam.Messaging.Plugin");
var emailMessenger = CrossMessaging.Current.EmailMessenger;
if (emailMessenger.CanSendEmail)
{
// Send simple e-mail to single receiver without attachments, bcc, cc etc.
emailMessenger.SendEmail("to.plugins#xamarin.com", "Xamarin Messaging Plugin", "Well hello there from Xam.Messaging.Plugin");
// Alternatively use EmailBuilder fluent interface to construct more complex e-mail with multiple recipients, bcc, attachments etc.
var email = new EmailMessageBuilder()
.To("to.plugins#xamarin.com")
.Cc("cc.plugins#xamarin.com")
.Bcc(new[] { "bcc1.plugins#xamarin.com", "bcc2.plugins#xamarin.com" })
.Subject("Xamarin Messaging Plugin")
.Body("Well hello there from Xam.Messaging.Plugin")
.Build();
emailMessenger.SendEmail(email);
}

How to intercept incoming email and retrieve message body in thunderbird

In my Thunderbird add-on I want to listen to new incoming emails and process the message body.
So I have written a mailListener and added it to an instance of nsIMsgFolderNotificationService.
The listener works fine and notifies when a mail comes. I get the nsIMsgDBHdr object which was fetched, but I cannot stream the message for the particular folder in the msgAdded function of my mailListener. it hangs, and I cannot even see the message body in the Thunderbird's message pane.
I think the nsISyncStreamListener used to stream the message from the folder waits for OnDataAvailable event which is not yet triggered inside the mailListener's msgAdded function.
Any inputs on how to fetch message body when a new email comes? Below is the code for my mailListener
var newMailListener = {
msgAdded: function(aMsgHdr) {
if( !aMsgHdr.isRead ){
let folder = aMsgHdr.folder;
if(aMsgHdr.recipients == "myemail+special#gmail.com"){
let messenger = Components.classes["#mozilla.org/messenger;1"]
.createInstance(Components.interfaces.nsIMessenger);
let listener = Components.classes["#mozilla.org/network/sync-stream-listener;1"]
.createInstance(Components.interfaces.nsISyncStreamListener);
let uri = aMsgHdr.folder.getUriForMsg(aMsgHdr);
messenger.messageServiceFromURI(uri).streamMessage(uri, listener, null, null, false, "");
let messageBody = aMsgHdr.folder.getMsgTextFromStream(listener.inputStream,
aMsgHdr.Charset,
65536,
32768,
false,
true,
{ });
alert("the message body : " + messageBody);
}
}
}
};
I had a similar problem. The solution I found (not easily) is to use MsgHdrToMimeMessage from mimemsg.js as Gloda is not available yet. This uses the callback function:
var newMailListener = {
msgAdded: function(aMsgHdr) {
if( !aMsgHdr.isRead ){
MsgHdrToMimeMessage(aMsgHdr, null, function (aMsgHdr, aMimeMessage) {
// do something with aMimeMessage:
alert("the message body : " + aMimeMessage.coerceBodyToPlaintext());
//alert(aMimeMessage.allUserAttachments.length);
//alert(aMimeMessage.size);
}, true);
}
}
};
And do not forget to include the necessary module:
Components.utils.import("resource:///modules/gloda/mimemsg.js");
More folow up reading can be found e. g. here.

Error while trying to use the "reply-to" in google apps script

I'm using google apps script to get the responses of a specific form in an specific e-mail,
What I'm trying to do is use a google form to open support tickets, so people need fill some fields like, title, description and e-mail,
And when they submit the form, it will automatically open a ticket, but the e-mail will be always from the owner of the form, and this was a problem because we want that the person who opened the ticket receives email updates, so what I'm trying to do is this:
I put a field in the form asking the persons email, and I'm trying to put that e-mail into the reply-to...
And apparently I'm in the right way to catch that e-mail but the reply-to don't show the email that the persons filled the box, it appears an error: [Ljava.lang.Object;#34dfe075
Does any one can help me?
Here is my script:
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
var email = "support#email.com";
var form = e.namedValues;
var subject = form["Title"];
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] && (e.namedValues[key] != "") ) {
message += key + ' :: '+ e.namedValues[key] + "\n\n";
}
}
GmailApp.sendEmail(email, subject, message, {replyTo: form["E-mail"], from: "support#email.com"});
} catch (e) {
Logger.log(e.toString());
}
}
And here is the output of this:
from: support#email.com
reply-to: [Ljava.lang.Object;#34dfe075
to: support#email.com
date: Fri, Oct 17, 2014 at 10:55 AM
subject: New Test
The reply to, is broken :(
The values returned in the e.namedValues property are arrays, so you must access them as such.
Modify your sendEmail line as follows:
GmailApp.sendEmail(email, subject, message, {replyTo: form["E-mail"][0], from: "support#email.com"});
Note the [0] array index on the form["E-Mail"] field, indicating you want the first value in that array, which will be the email address entered.
See the example next to "e.namedValues" here: https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events

Google Form Email Notification On Submission

I'm trying to update this script to allow me to update the "Sender's" or "Reply To" email address. I'm unsure how to do this as I'm using the script listed here - http://www.labnol.org/?p=20884
I've emailed the developer of this script but have yet to receive a response. Any advice on adding a field to overwrite the default "Reply To" or sender email address?
Thanks for your help!
/* Send Google Form by Email v2.0 */
/* For customization, contact the developer at amit#labnol.org */
/* Tutorial: http://www.labnol.org/?p=20884 */
function Initialize() {
var triggers = ScriptApp.getScriptTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
// You may replace this with another email address
var email = "CLIENT EMAIL ADDRESS";
// Optional but change the following variable
// to have a custom subject for Google Form email notifications
var subject = "Form Application Submitted";
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
// Only include form fields that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] && (e.namedValues[key] != "") ) {
message += key + ' :: '+ e.namedValues[key] + "\n\n";
}
}
// This is the MailApp service of Google Apps Script
// that sends the email. You can also use GmailApp for HTML Mail.
MailApp.sendEmail(email, subject, message);
} catch (e) {
Logger.log(e.toString());
}
}
Replace
MailApp.sendEmail(email, subject, message);
with
GmailApp.sendEmail(email, subject, message, {replyTo: "abc#example.com", from: "xyz#example.com"});
The from address has to be an alias though.