Chilkat Examples

ChilkatHOMEAndroid™Classic ASPCC++C#Mono C#.NET Core C#C# UWP/WinRTDataFlexDelphi ActiveXDelphi DLLVisual FoxProJavaLianjaMFCObjective-CPerlPHP ActiveXPHP ExtensionPowerBuilderPowerShellPureBasicCkPythonChilkat2-PythonRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++Visual Basic 6.0VB.NETVB.NET UWP/WinRTVBScriptXojo PluginNode.jsExcelGo

MFC Examples

Web API Categories

ASN.1
Amazon EC2
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Service Bus
Azure Table Service
Base64
Bounced Email
Box
CAdES
CSR
CSV
Certificates
Compression
DKIM / DomainKey
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
EBICS
ECC
Ed25519
Email Object
Encryption
FTP
FileAccess
Firebase
GMail REST API
GMail SMTP/IMAP/POP
Geolocation
Google APIs
Google Calendar
Google Cloud SQL
Google Cloud Storage
Google Drive
Google Photos
Google Sheets
Google Tasks
Gzip
HTML-to-XML/Text
HTTP

HTTP Misc
IMAP
JSON
JSON Web Encryption (JWE)
JSON Web Signatures (JWS)
JSON Web Token (JWT)
Java KeyStore (JKS)
MHT / HTML Email
MIME
MS Storage Providers
Microsoft Graph
NTLM
OAuth1
OAuth2
OIDC
Office365
OneDrive
OpenSSL
Outlook
Outlook Calendar
Outlook Contact
PDF Signatures
PEM
PFX/P12
PKCS11
POP3
PRNG
REST
REST Misc
RSA
SCP
SCard
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
ScMinidriver
SharePoint
Socket/SSL/TLS
Spider
Stream
Tar Archive
Upload
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Zip
curl

 

 

 

(MFC) Outlook -- Create Reply Email, Update, and Send

Creates a reply email in the Drafts folder, updates the reply with information, and then sends the reply.

Note: This example requires Chilkat v9.5.0.68 or greater.

This example applies to: Exchange Online | Office 365 | Hotmail.com | Live.com | MSN.com | Outlook.com | Passport.com

Chilkat C/C++ Library Downloads

MS Visual C/C++ Libs

See Also: Using MFC CString in Chilkat

#include <CkHttp.h>
#include <CkHashtable.h>
#include <CkStringBuilder.h>
#include <CkJsonObject.h>
#include <CkHttpResponse.h>

void ChilkatSample(void)
    {
    CkString strOut;

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    CkHttp http;

    // Use your previously obtained access token here:
    http.put_AuthToken("MICROSOFT_GRAPH_ACCESS_TOKEN");

    // This example will search /Inbox for a message that will be replied to.
    // First we need to get the folder ID for /Inbox.
    // Then we'll search for messages based on some criteria, and reply to the 1st matching message.
    // To reply, we'll create the reply message in the Drafts folder, update it with content, and the send.

    // Get the folder ID for /Inbox from the folder map created by this example 
    CkHashtable htFolderMap;
    CkStringBuilder sbMap;
    sbMap.LoadFile("qa_data/outlook/folderMap.xml","utf-8");
    htFolderMap.AddFromXmlSb(sbMap);

    // Get the ID for the "/Inbox" folder:
    const char *folderId = htFolderMap.lookupStr("/Inbox");
    if (htFolderMap.get_LastMethodSuccess() != true) {
        strOut.append("Folder ID not found");
        strOut.append("\r\n");
        SetDlgItemText(IDC_EDIT1,strOut.getUnicode());
        return;
    }

    bool success = true;
    CkJsonObject json;
    json.put_EmitCompact(false);

    // Search for unread emails in this folder from support@chilkatsoft.com 
    http.SetUrlVar("folder_id",folderId);
    http.SetUrlVar("select","id,subject");
    http.SetUrlVar("filter","(isRead eq false) and (from/emailAddress/address eq 'support@chilkatsoft.com')");

    CkStringBuilder sbResponse;
    success = http.QuickGetSb("https://graph.microsoft.com/v1.0/me/mailFolders/{$folder_id}/messages?$filter={$filter}&$select={$select}",sbResponse);
    if (success != true) {
        strOut.append(http.lastErrorText());
        strOut.append("\r\n");
        SetDlgItemText(IDC_EDIT1,strOut.getUnicode());
        return;
    }

    json.LoadSb(sbResponse);
    // Show the results..
    strOut.append(json.emit());
    strOut.append("\r\n");

    if (json.SizeOfArray("value") == 0) {
        strOut.append("Empty result set.");
        strOut.append("\r\n");
        SetDlgItemText(IDC_EDIT1,strOut.getUnicode());
        return;
    }

    // Sample results:

    // {
    //   "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('me')/mailFolders('AQMkADAwATM0MDAAMS1iNTcwLWI2NTEtMDACLTAwCgAuAAADsVyfxjDU406Ic4X7ill8xAEA5_vF7TKKdE6bGCRqXyl2PQAAAgEMAAAA')/messages(id,subject)",
    //   "value": [
    //     {
    //       "@odata.etag": "W/\"CQAAABYAAADn68XtMop0TpsYJGpfKXY9AADOpwfq\"",
    //       "id": "AQMkADAwATM0MDAAMS1iNTcwLWI2NTEtMDACLTAwCgBGAAADsVyfxjDU406Ic4X7ill8xAcA5_vF7TKKdE6bGCRqXyl2PQAAAgEMAAAA5_vF7TKKdE6bGCRqXyl2PQAAAM6Jj1wAAAA=",
    //       "subject": "This email contains a PDF attachment"
    //     },
    //     {
    //       "@odata.etag": "W/\"CQAAABYAAADn68XtMop0TpsYJGpfKXY9AADOpwfs\"",
    //       "id": "AQMkADAwATM0MDAAMS1iNTcwLWI2NTEtMDACLTAwCgBGAAADsVyfxjDU406Ic4X7ill8xAcA5_vF7TKKdE6bGCRqXyl2PQAAAgEMAAAA5_vF7TKKdE6bGCRqXyl2PQAAAM6Jj14AAAA=",
    //       "subject": "This email has the word Amazon in the subject.."
    //     }
    //   ]
    // }

    // We'll create a reply for the 1st message in the result set.
    // We'll need the message existing id.

    const char *existingMsgId = json.stringOf("value[0].id");

    // To create a reply, send a request such as the following:

    // 	POST https://graph.microsoft.com/v1.0/me/messages/{id}/createReply
    // 	Content-type: application/json
    // 	Content-length: 248
    // 
    // 	{
    // 	  "comment": "comment-value"
    // 	}

    CkJsonObject jsonRequestBody;
    jsonRequestBody.UpdateString("comment","This is a comment");

    http.SetUrlVar("message_id",existingMsgId);

    // Create the reply in the Drafts folder:
    CkHttpResponse *resp = http.PostJson2("https://graph.microsoft.com/v1.0/me/messages/{$message_id}/createReply","application/json",jsonRequestBody.emit());
    if (http.get_LastMethodSuccess() != true) {
        strOut.append(http.lastErrorText());
        strOut.append("\r\n");
        SetDlgItemText(IDC_EDIT1,strOut.getUnicode());
        return;
    }

    // A 201 response indicates success.
    if (resp->get_StatusCode() == 201) {
        strOut.append("Created reply draft.");
        strOut.append("\r\n");
        success = true;
    }
    else {
        strOut.append("Response status code = ");
        strOut.appendInt(resp->get_StatusCode());
        strOut.append("\r\n");
        strOut.append("Failed to create reply draft.");
        strOut.append("\r\n");
        success = false;
    }

    // Show the response in both cases..
    CkJsonObject jsonResponse;
    jsonResponse.put_EmitCompact(false);
    jsonResponse.Load(resp->bodyStr());
    strOut.append(jsonResponse.emit());
    strOut.append("\r\n");

    delete resp;
    if (success == false) {
        SetDlgItemText(IDC_EDIT1,strOut.getUnicode());
        return;
    }

    // ----------------------------------------------
    // Get the message id of the newly created reply.
    const char *replyMsgId = jsonResponse.stringOf("id");

    // Update the message with new text in the body..
    // Send an HTTP PATCH request that looks something like this:
    // Only send the message parts that are changing.

    // 	PATCH https://graph.microsoft.com/v1.0/me/messages/{reply_message_id}
    // 	Content-type: application/json
    // 	Content-length: 248
    // 
    // 	{
    // 	  "subject": "subject-value",
    // 	  "body": {
    // 	    "contentType": "html",
    // 	    "content": "updated HTML goes here"
    // 	  },
    // 	  "inferenceClassification": "other"
    // 	}

    CkJsonObject jsonPatch;
    jsonPatch.UpdateString("body.contentType","html");

    // The reply email that Outlook created will contain the original message under a horizontal rule.
    // The body.content should contain this substring:  "<body bgcolor=\"#FFFFFF\">\r\n<hr "
    // We're going to insert our reply after the body tag, and before the hr tag.
    CkStringBuilder sbHtml;
    jsonResponse.StringOfSb("body.content",sbHtml);
    // Insert the response HTML in the reply HTML body.
    int numReplaced = sbHtml.ReplaceBetween("<body bgcolor=\"#FFFFFF\">","<hr ","\r\n","<p>This is my response.</p>");
    if (numReplaced != 1) {
        strOut.append("Something is amiss!");
        strOut.append("\r\n");
        SetDlgItemText(IDC_EDIT1,strOut.getUnicode());
        return;
    }

    jsonPatch.UpdateString("body.content",sbHtml.getAsString());

    // Add additional CC, BCC, or TO recipients like this:
    int numToRecipients = jsonResponse.SizeOfArray("toRecipients");
    int i = 0;
    // Copy existing TO recipients.
    while (i < numToRecipients) {
        jsonPatch.put_I(i);
        jsonResponse.put_I(i);
        jsonPatch.UpdateString("toRecipients[i].emailAddress.name",jsonResponse.stringOf("toRecipients[i].emailAddress.name"));
        jsonPatch.UpdateString("toRecipients[i].emailAddress.address",jsonResponse.stringOf("toRecipients[i].emailAddress.address"));
        i = i + 1;
    }

    // Add an additional TO recipient.
    jsonPatch.put_I(numToRecipients);
    jsonPatch.UpdateString("toRecipients[i].emailAddress.name","Chilkat");
    jsonPatch.UpdateString("toRecipients[i].emailAddress.address","admin@chilkat.io");

    int numCcRecipients = jsonResponse.SizeOfArray("ccRecipients");
    i = 0;
    // Copy existing CC recipients.
    while (i < numCcRecipients) {
        jsonPatch.put_I(i);
        jsonResponse.put_I(i);
        jsonPatch.UpdateString("ccRecipients[i].emailAddress.name",jsonResponse.stringOf("ccRecipients[i].emailAddress.name"));
        jsonPatch.UpdateString("ccRecipients[i].emailAddress.address",jsonResponse.stringOf("ccRecipients[i].emailAddress.address"));
        i = i + 1;
    }

    // Add an additional CC recipient.
    jsonPatch.put_I(numCcRecipients);
    jsonPatch.UpdateString("ccRecipients[i].emailAddress.name","Chilkat GMail");
    jsonPatch.UpdateString("ccRecipients[i].emailAddress.address","chilkat.support@gmail.com");

    jsonPatch.put_EmitCompact(false);
    strOut.append(jsonPatch.emit());
    strOut.append("\r\n");

    http.SetUrlVar("message_id",replyMsgId);
    resp = http.PText("PATCH","https://graph.microsoft.com/v1.0/me/messages/{$message_id}",jsonPatch.emit(),"utf-8","application/json",false,false);
    if (http.get_LastMethodSuccess() != true) {
        strOut.append(http.lastErrorText());
        strOut.append("\r\n");
        SetDlgItemText(IDC_EDIT1,strOut.getUnicode());
        return;
    }

    // A 200 response indicates success.
    if (resp->get_StatusCode() == 200) {
        strOut.append("Patched the reply draft.");
        strOut.append("\r\n");
        success = true;
    }
    else {
        strOut.append("Response status code = ");
        strOut.appendInt(resp->get_StatusCode());
        strOut.append("\r\n");
        strOut.append("Failed to patch the reply draft.");
        strOut.append("\r\n");
        success = false;
    }

    // Show the response in both cases..
    jsonResponse.Load(resp->bodyStr());
    strOut.append(jsonResponse.emit());
    strOut.append("\r\n");

    delete resp;
    if (success == false) {
        SetDlgItemText(IDC_EDIT1,strOut.getUnicode());
        return;
    }

    // ---------------------------------------------------------------------
    // OK, let's send the reply email...
    // To send, POST with an empty request body:
    // POST https://graph.microsoft.com/v1.0/me/messages/{id}/send

    resp = http.PText("POST","https://graph.microsoft.com/v1.0/me/messages/{$message_id}/send","","","",false,false);
    if (http.get_LastMethodSuccess() != true) {
        strOut.append(http.lastErrorText());
        strOut.append("\r\n");
        SetDlgItemText(IDC_EDIT1,strOut.getUnicode());
        return;
    }

    // A 202 response indicates success.
    if (resp->get_StatusCode() == 202) {
        strOut.append("Sent the email reply.");
        strOut.append("\r\n");
        // If the status code was 202, there is no response body.
    }
    else {
        strOut.append("Response status code = ");
        strOut.appendInt(resp->get_StatusCode());
        strOut.append("\r\n");
        strOut.append("Failed to send the email reply.");
        strOut.append("\r\n");
        jsonResponse.Load(resp->bodyStr());
        strOut.append(jsonResponse.emit());
        strOut.append("\r\n");
    }

    delete resp;

    strOut.append("Finished.");
    strOut.append("\r\n");

    // -----------------------------------------------------------------------
    // A sample successful JSON response for the createReply looks like this:

    // 	{
    // 	  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#message",
    // 	  "@odata.type": "#microsoft.graph.message",
    // 	  "@odata.etag": "W/\"CQAAABYAAADn68XtMop0TpsYJGpfKXY9AADQAwR4\"",
    // 	  "id": "AQMkADAwATM0MDAAMS1iNTcwLWI2NTEtMDACLTAwCgBGAAADsVyfxjDU406Ic4X7ill8xAcA5_vF7TKKdE6bGCRqXyl2PQAAAgEPAAAA5_vF7TKKdE6bGCRqXyl2PQAAAM-lQbAAAAA=",
    // 	  "createdDateTime": "2017-06-01T14:31:56Z",
    // 	  "lastModifiedDateTime": "2017-06-01T14:31:56Z",
    // 	  "changeKey": "CQAAABYAAADn68XtMop0TpsYJGpfKXY9AADQAwR4",
    // 	  "categories": [
    // 	  ],
    // 	  "receivedDateTime": "2017-06-01T14:31:56Z",
    // 	  "sentDateTime": "2017-06-01T14:31:56Z",
    // 	  "hasAttachments": false,
    // 	  "internetMessageId": "<SN1PR20MB0461AF40FC899A8462536F04E6F60@SN1PR20MB0461.namprd20.prod.outlook.com>",
    // 	  "subject": "RE: This email contains a PDF attachment",
    // 	  "bodyPreview": "________________________________\r\nFrom: Chilkat Software <support@chilkatsoft.com>\r\nSent: Tuesday, May 30, 2017 10:58:56 PM\r\nTo: chilkatsoft@outlook.com\r\nSubject: This email contains a PDF attachment\r\n\r\nThis email contains a PDF attachment\r\n--\r\nBest Regar",
    // 	  "importance": "normal",
    // 	  "parentFolderId": "AQMkADAwATM0MDAAMS1iNTcwLWI2NTEtMDACLTAwCgAuAAADsVyfxjDU406Ic4X7ill8xAEA5_vF7TKKdE6bGCRqXyl2PQAAAgEPAAAA",
    // 	  "conversationId": "AQQkADAwATM0MDAAMS1iNTcwLWI2NTEtMDACLTAwCgAQAMMaWY-CWmVOqNKt-NiVhkU=",
    // 	  "isDeliveryReceiptRequested": false,
    // 	  "isReadReceiptRequested": false,
    // 	  "isRead": true,
    // 	  "isDraft": true,
    // 	  "webLink": "https://outlook.live.com/owa/?ItemID=AQMkADAwATM0MDAAMS1iNTcwLWI2NTEtMDACLTAwCgBGAAADsVyfxjDU406Ic4X7ill8xAcA5%2BvF7TKKdE6bGCRqXyl2PQAAAgEPAAAA5%2BvF7TKKdE6bGCRqXyl2PQAAAM%2FlQbAAAAA%3D&exvsurl=1&viewmodel=ReadMessageItem",
    // 	  "inferenceClassification": "focused",
    // 	  "body": {
    // 	    "contentType": "html",
    // 	    "content": "<html>\r\n<head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n<meta content=\"text/html; charset=us-ascii\">\r\n<meta content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body bgcolor=\"#FFFFFF\">\r\n<hr tabindex=\"-1\" style=\"display:inline-block; width:98%\"> ... </html>\r\n"
    // 	  },
    // 	  "sender": {
    // 	    "emailAddress": {
    // 	      "name": "Matt Smith",
    // 	      "address": "chilkatsoft@outlook.com"
    // 	    }
    // 	  },
    // 	  "from": {
    // 	    "emailAddress": {
    // 	      "name": "Matt Smith",
    // 	      "address": "chilkatsoft@outlook.com"
    // 	    }
    // 	  },
    // 	  "toRecipients": [
    // 	    {
    // 	      "emailAddress": {
    // 	        "name": "Chilkat Software",
    // 	        "address": "support@chilkatsoft.com"
    // 	      }
    // 	    }
    // 	  ],
    // 	  "ccRecipients": [
    // 	  ],
    // 	  "bccRecipients": [
    // 	  ],
    // 	  "replyTo": [
    // 	  ]
    // 	}
    // 

    // -----------------------------------------------------------------------
    // A sample successful PATCH JSON response looks like this:

    // 	{
    // 	  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('admin%40chilkat.io')/messages/$entity",
    // 	  "@odata.etag": "W/\"CQAAABYAAADn68XtMop0TpsYJGpfKXY9AADQAwSA\"",
    // 	  "id": "AQMkADAwATM0MDAAMS1iNTcwLWI2NTEtMDACLTAwCgBGAAADsVyfxjDU406Ic4X7ill8xAcA5_vF7TKKdE6bGCRqXyl2PQAAAgEPAAAA5_vF7TKKdE6bGCRqXyl2PQAAAM-lQbMAAAA=",
    // 	  "createdDateTime": "2017-06-01T15:18:14Z",
    // 	  "lastModifiedDateTime": "2017-06-01T15:18:17Z",
    // 	  "changeKey": "CQAAABYAAADn68XtMop0TpsYJGpfKXY9AADQAwSA",
    // 	  "categories": [
    // 	  ],
    // 	  "receivedDateTime": "2017-06-01T15:18:15Z",
    // 	  "sentDateTime": "2017-06-01T15:18:15Z",
    // 	  "hasAttachments": false,
    // 	  "internetMessageId": "<SN1PR20MB046138C4A26051200764FE38E6F60@SN1PR20MB0461.namprd20.prod.outlook.com>",
    // 	  "subject": "RE: This email has the word Amazon in the subject..",
    // 	  "bodyPreview": "This is my response.\r\n\r\n________________________________\r\nFrom: Chilkat Software <support@chilkatsoft.com>\r\nSent: Tuesday, May 30, 2017 11:40:01 PM\r\nTo: Chilkat Software\r\nSubject: This email has the word Amazon in the subject..\r\n\r\nThis email has the word ",
    // 	  "importance": "normal",
    // 	  "parentFolderId": "AQMkADAwATM0MDAAMS1iNTcwLWI2NTEtMDACLTAwCgAuAAADsVyfxjDU406Ic4X7ill8xAEA5_vF7TKKdE6bGCRqXyl2PQAAAgEPAAAA",
    // 	  "conversationId": "AQQkADAwATM0MDAAMS1iNTcwLWI2NTEtMDACLTAwCgAQAE64PfPP1n1IhU4YasnNN0Q=",
    // 	  "isDeliveryReceiptRequested": false,
    // 	  "isReadReceiptRequested": false,
    // 	  "isRead": true,
    // 	  "isDraft": true,
    // 	  "webLink": "https://outlook.live.com/owa/?ItemID=AQMkADAwATM0MDAAMS1iNTcwLWI2NTEtMDACLTAwCgBGAAADsVyfxjDU406Ic4X7ill8xAcA5%2BvF7TKKdE6bGCRqXyl2PQAAAgEPAAAA5%2BvF7TKKdE6bGCRqXyl2PQAAAM%2FlQbMAAAA%3D&exvsurl=1&viewmodel=ReadMessageItem",
    // 	  "inferenceClassification": "focused",
    // 	  "body": {
    // 	    "contentType": "html",
    // 	    "content": "<html>\r\n<head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n<meta content=\"text/html; charset=us-ascii\">\r\n<meta content=\"text/html; charset=us-ascii\">\r\n<meta content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body bgcolor=\"#FFFFFF\">\r\n<p>This is my response.</p>\r\n<hr tabindex=\"-1\" style=\"display:inline-block; width:98%\">\r\n<div id=\"divRplyFwdMsg\" dir=\"ltr\"><font face=\"Calibri, sans-serif\" color=\"#000000\" style=\"font-size:11pt\"><b>From:</b> Chilkat Software &lt;support@chilkatsoft.com&gt;<br>\r\n<b>Sent:</b> Tuesday, May 30, 2017 11:40:01 PM<br>\r\n<b>To:</b> Chilkat Software<br>\r\n<b>Subject:</b> This email has the word Amazon in the subject..</font>\r\n<div>&nbsp;</div>\r\n</div>\r\n<div><font face=\"Calibri\">This email has the word Amazon in the subject..</font><br>\r\n<div class=\"moz-signature\">-- <br>\r\nBest Regards,<br>\r\nMatt Smith<br>\r\nChilkat Software, Inc.<br>\r\n<p><a href=\"https://twitter.com/chilkatsoft\">Follow Chilkat on Twitter</a> </p>\r\n</div>\r\n</div>\r\n</body>\r\n</html>\r\n"
    // 	  },
    // 	  "sender": {
    // 	    "emailAddress": {
    // 	      "name": "Matt Smith",
    // 	      "address": "chilkatsoft@outlook.com"
    // 	    }
    // 	  },
    // 	  "from": {
    // 	    "emailAddress": {
    // 	      "name": "Matt Smith",
    // 	      "address": "chilkatsoft@outlook.com"
    // 	    }
    // 	  },
    // 	  "toRecipients": [
    // 	    {
    // 	      "emailAddress": {
    // 	        "name": "Chilkat Software",
    // 	        "address": "support@chilkatsoft.com"
    // 	      }
    // 	    }
    // 	  ],
    // 	  "ccRecipients": [
    // 	  ],
    // 	  "bccRecipients": [
    // 	  ],
    // 	  "replyTo": [
    // 	  ]
    // 	}


    SetDlgItemText(IDC_EDIT1,strOut.getUnicode());

    }

 

© 2000-2022 Chilkat Software, Inc. All Rights Reserved.