Zig Requires Chilkat v11.0.0+
Zig
Outlook -- Create Reply Email, Update, and Send
See more Outlook Examples
Creates a reply email in the Drafts folder, updates the reply with information, and then sends the reply.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
var success: bool = false;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const http = try chilkat.Http.init();
defer http.deinit();
// Use your previously obtained access token here:
http.setAuthToken("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
const ht_folder_map = try chilkat.Hashtable.init();
defer ht_folder_map.deinit();
const sb_map = try chilkat.StringBuilder.init();
defer sb_map.deinit();
sb_map.loadFile("qa_data/outlook/folderMap.xml", "utf-8") catch {};
ht_folder_map.addFromXmlSb(sb_map) catch {};
// Get the ID for the "/Inbox" folder:
const folder_id = ht_folder_map.lookupStr(alloc, "/Inbox") catch {
std.debug.print("Folder ID not found\n", .{});
return;
};
success = true;
const json = try chilkat.JsonObject.init();
defer json.deinit();
json.setEmitCompact(false);
// Search for unread emails in this folder from support@chilkatsoft.com
http.setUrlVar("folder_id", folder_id) catch {};
http.setUrlVar("select", "id,subject") catch {};
http.setUrlVar("filter", "(isRead eq false) and (from/emailAddress/address eq 'support@chilkatsoft.com')") catch {};
const sb_response = try chilkat.StringBuilder.init();
defer sb_response.deinit();
success = if (http.quickGetSb("https://graph.microsoft.com/v1.0/me/mailFolders/{$folder_id}/messages?$filter={$filter}&$select={$select}", sb_response)) true else |_| false;
if (!success) {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
}
json.loadSb(sb_response) catch {};
// Show the results..
std.debug.print("{s}\n", .{try json.emit(alloc)});
if (json.sizeOfArray("value") == 0) {
std.debug.print("Empty result set.\n", .{});
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 existing_msg_id = try json.stringOf(alloc, "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"
// }
const json_request_body = try chilkat.JsonObject.init();
defer json_request_body.deinit();
json_request_body.updateString("comment", "This is a comment") catch {};
http.setUrlVar("message_id", existing_msg_id) catch {};
// Create the reply in the Drafts folder:
const resp = try chilkat.HttpResponse.init();
defer resp.deinit();
success = if (http.httpJson("POST", "https://graph.microsoft.com/v1.0/me/messages/{$message_id}/createReply", json_request_body, "application/json", resp)) true else |_| false;
if (!success) {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
}
// A 201 response indicates success.
if (resp.getStatusCode() == 201) {
std.debug.print("Created reply draft.\n", .{});
success = true;
} else {
std.debug.print("Response status code = {d}\n", .{resp.getStatusCode()});
std.debug.print("Failed to create reply draft.\n", .{});
success = false;
}
// Show the response in both cases..
const json_response = try chilkat.JsonObject.init();
defer json_response.deinit();
json_response.setEmitCompact(false);
json_response.load(try resp.getBodyStr(alloc)) catch {};
std.debug.print("{s}\n", .{try json_response.emit(alloc)});
if (!success) {
return;
}
// ----------------------------------------------
// Get the message id of the newly created reply.
const reply_msg_id = try json_response.stringOf(alloc, "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"
// }
const json_patch = try chilkat.JsonObject.init();
defer json_patch.deinit();
json_patch.updateString("body.contentType", "html") catch {};
// 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.
const sb_html = try chilkat.StringBuilder.init();
defer sb_html.deinit();
json_response.stringOfSb("body.content", sb_html) catch {};
// Insert the response HTML in the reply HTML body.
const num_replaced = sb_html.replaceBetween("<body bgcolor=\"#FFFFFF\">", "<hr ", "\r\n", "<p>This is my response.</p>");
if (num_replaced != 1) {
std.debug.print("Something is amiss!\n", .{});
return;
}
json_patch.updateString("body.content", try sb_html.getAsString(alloc)) catch {};
// Add additional CC, BCC, or TO recipients like this:
const num_to_recipients = json_response.sizeOfArray("toRecipients");
var i: i32 = 0;
// Copy existing TO recipients.
while (i < num_to_recipients) {
json_patch.setI(i);
json_response.setI(i);
json_patch.updateString("toRecipients[i].emailAddress.name", try json_response.stringOf(alloc, "toRecipients[i].emailAddress.name")) catch {};
json_patch.updateString("toRecipients[i].emailAddress.address", try json_response.stringOf(alloc, "toRecipients[i].emailAddress.address")) catch {};
i = i + 1;
}
// Add an additional TO recipient.
json_patch.setI(num_to_recipients);
json_patch.updateString("toRecipients[i].emailAddress.name", "Chilkat") catch {};
json_patch.updateString("toRecipients[i].emailAddress.address", "admin@chilkat.io") catch {};
const num_cc_recipients = json_response.sizeOfArray("ccRecipients");
i = 0;
// Copy existing CC recipients.
while (i < num_cc_recipients) {
json_patch.setI(i);
json_response.setI(i);
json_patch.updateString("ccRecipients[i].emailAddress.name", try json_response.stringOf(alloc, "ccRecipients[i].emailAddress.name")) catch {};
json_patch.updateString("ccRecipients[i].emailAddress.address", try json_response.stringOf(alloc, "ccRecipients[i].emailAddress.address")) catch {};
i = i + 1;
}
// Add an additional CC recipient.
json_patch.setI(num_cc_recipients);
json_patch.updateString("ccRecipients[i].emailAddress.name", "Chilkat GMail") catch {};
json_patch.updateString("ccRecipients[i].emailAddress.address", "chilkat.support@gmail.com") catch {};
json_patch.setEmitCompact(false);
std.debug.print("{s}\n", .{try json_patch.emit(alloc)});
http.setUrlVar("message_id", reply_msg_id) catch {};
success = if (http.httpJson("PATCH", "https://graph.microsoft.com/v1.0/me/messages/{$message_id}", json_patch, "application/json", resp)) true else |_| false;
if (!success) {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
}
// A 200 response indicates success.
if (resp.getStatusCode() == 200) {
std.debug.print("Patched the reply draft.\n", .{});
success = true;
} else {
std.debug.print("Response status code = {d}\n", .{resp.getStatusCode()});
std.debug.print("Failed to patch the reply draft.\n", .{});
success = false;
}
// Show the response in both cases..
json_response.load(try resp.getBodyStr(alloc)) catch {};
std.debug.print("{s}\n", .{try json_response.emit(alloc)});
if (!success) {
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
http.httpStr("POST", "https://graph.microsoft.com/v1.0/me/messages/{$message_id}/send", "", "", "", resp) catch {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
};
// A 202 response indicates success.
if (resp.getStatusCode() == 202) {
std.debug.print("Sent the email reply.\n", .{});
// If the status code was 202, there is no response body.
} else {
std.debug.print("Response status code = {d}\n", .{resp.getStatusCode()});
std.debug.print("Failed to send the email reply.\n", .{});
json_response.load(try resp.getBodyStr(alloc)) catch {};
std.debug.print("{s}\n", .{try json_response.emit(alloc)});
}
std.debug.print("Finished.\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 <support@chilkatsoft.com><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> </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": [
// ]
// }
}