Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have created on outlook web addin to print mail in custom format , but if mail contains images,that images are not displayed , following is my code ,
<script type="text/javascript">
    // The Office initialize function must be run each time a new page is loaded.
    Office.onReady(function (info) {
        if (info.host === Office.HostType.Outlook) {
            // Your Office-specific code here
            initializePage();
        }
    });
    // Call the initializePage() function when the page loads
    var selectedCheckboxes = []; // Array to store the sequence of selected checkboxes

    function CreateContent(checkboxId) {

        const checkbox = document.getElementById(checkboxId);
        const isChecked = checkbox.checked;

        if (isChecked) {
            selectedCheckboxes.push(checkboxId);
        }

        // Update the checkbox sequence in local storage
        localStorage.setItem("selectedCheckboxes", JSON.stringify(selectedCheckboxes));
        PrintFormat();


    }

    function getEmailAddresses(emailArray) {
        return emailArray.map(function (address) {
            return address.displayName;
        }).join(', ');
    }

    function getAttachments(attachmentArray) {
        return attachmentArray.map(function (attachment) {
            return attachment.name;
        }).join(', ');
    }
    // Function to load and set checkbox states from local storage
    function loadCheckboxStates() {
        // Load the sequence of selected checkboxes from local storage
        const savedCheckboxes = JSON.parse(localStorage.getItem("selectedCheckboxes")) || [];
        const checkboxes = document.querySelectorAll("input[type=checkbox]");

        checkboxes.forEach(function (checkbox) {
            const checkboxId = checkbox.id;
            checkbox.checked = savedCheckboxes.includes(checkboxId);
        });

        selectedCheckboxes = savedCheckboxes;
        PrintFormat();
    }

    function PrintFormat() {
        var customContent = "<div>";


        selectedCheckboxes.forEach(checkbox => {
            switch (checkbox) {
                case "fromCheckbox":
                    customContent += "<p style=\"font-family: Arial Black;margin: 0; padding - top: 0;\">From: " + Office.context.mailbox.item.from.displayName + "</p>";
                    break;
                case "toCheckbox":
                    customContent += "<p style=\"font-family: Arial Black;margin: 0; padding - top: 0;\">To:" + getEmailAddresses(Office.context.mailbox.item.to) + "</p>";
                    break;
                case "ccCheckbox":
                    customContent += "<p style=\"font-family: Arial Black;margin: 0; padding - top: 0;\">cc:  " + getEmailAddresses(Office.context.mailbox.item.cc) + "</p>";
                    break;
                case "subjectCheckbox":
                    customContent += "<p style=\"font-family: Arial Black;margin: 0; padding - top: 0;\">Subject: " + Office.context.mailbox.item.subject + "</p>";
                    break;
                case "dateCheckbox":

                    const emailDate = new Date(Office.context.mailbox.item.dateTimeCreated);
                    const daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
                    const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

                    const formattedDate = daysOfWeek[emailDate.getDay()] + ", " +
                        months[emailDate.getMonth()] + " " +
                        emailDate.getDate() + ", " +
                        emailDate.getFullYear() + " " +
                        (emailDate.getHours() % 12 || 12) + ":" +
                        (emailDate.getMinutes() < 10 ? "0" : "") + emailDate.getMinutes() + " " +
                        (emailDate.getHours() < 12 ? "AM" : "PM");

                    customContent += "<p style=\"font-family: Arial Black;margin: 0; padding - top: 0;\">Date:" + formattedDate + "</p>";
                    break;
                case "priorityCheckbox":
                    if (Office.context.mailbox.item.importance != null) {
                        customContent += "<p style=\"font-family: Arial Black;margin: 0; padding - top: 0;\">Priority: " + Office.context.mailbox.item.importance + "</p>";
                    }
                    break;
                case "attachmentCheckbox":
                    if (Office.context.mailbox.item.attachments != null) {
                        customContent += "<p style=\"font-family: Arial Black;margin: 0; padding - top: 0;\">Attachment: " + getAttachments(Office.context.mailbox.item.attachments) + "</p>";
                    }
                    break;


            }
        });

        customContent += "</div>";

        document.getElementById("MailContent").innerHTML = customContent;
        // document.getElementById("MailContent").innerHTML += Office.context.mailbox.item.body.getAsync(Office.CoercionType.Html);
        console.log(customContent);
    }

    // Function to get image data as a base64-encoded string



    // Function to initialize the page
    function initializePage() {
        loadCheckboxStates();


    } // Function to handle images in the email body




    function onPrintButtonClick() {
        document.getElementById("Customisation").style.display = 'none';
        document.getElementById("ButtonsId").style.display = 'none';

        var emailBody = Office.context.mailbox.item.body.getAsync("html", function (result) {
            if (result.status === Office.AsyncResultStatus.Succeeded) {


                document.getElementById("emailBody").innerHTML = result.value;
                document.getElementById("emailBody").style.fontFamily = "Arial Black";
                document.getElementById("emailBody").style.fontSize = '20px';
                document.getElementById("emailBody").style.fontWeight = 'Bold';

                var emailBodyHtml = result.value;




                var tempDiv = document.createElement('div');
                tempDiv.innerHTML = emailBodyHtml;

                // Find and modify the font style
                var paragraphs = tempDiv.querySelectorAll('span, p, li, table, b');
                for (var i = 0; i < paragraphs.length; i++) {
                    paragraphs[i].style.fontFamily = 'Arial Black';
                    paragraphs[i].style.fontSize = '20px';
                    paragraphs[i].style.fontWeight = 'bold';
                }


                // Get the modified HTML back as a string
                var modifiedEmailBodyHtml = tempDiv.innerHTML;

                // Now you can use modifiedEmailBodyHtml to set the email body in your add-in
                document.getElementById('emailBody').innerHTML = modifiedEmailBodyHtml;
                console.log(document.getElementById('emailBody').innerHTML);

               window.print();
              //  var printWindow = window.open('', '_blank');

                //// Write the email content to the new window
                //printWindow.document.write(modifiedEmailBodyHtml);

                //// Ensure images are loaded before printing
                //printWindow.onload = function () {
                //    // Print the document after images are loaded
                //    printWindow.print();
                //};


            }
        });
        //Office.context.mailbox.item.body.getAsync(
        //    "html",
        //    { asyncContext: "Printing" },
        //    function (result) {
        //        if (result.status === Office.AsyncResultStatus.Succeeded) {
        //            var emailHtml = resolveCidReferences(result.value);

        //            // Create a new window for printing
        //            var printWindow = window.open('', '_blank');

        //            // Write the email content to the new window
        //            printWindow.document.write(emailHtml);

        //            // Ensure images are loaded before printing
        //            printWindow.onload = function () {
        //                // Print the document after images are loaded
        //                printWindow.print();
        //            };
        //        } else {
        //            console.error("Error retrieving email body: " + result.error.message);
        //        }
        //    }
        //);
    }


    function onResetButtonClick() {
        const checkboxes = document.querySelectorAll("input[type=checkbox]");

        checkboxes.forEach(function (checkbox) {
            checkbox.checked = false;
        });

        // Clear the selected checkboxes and remove from local storage
        selectedCheckboxes = [];
        localStorage.removeItem("selectedCheckboxes");

        document.getElementById("MailContent").innerHTML = "";
    }

</script>


What I have tried:

function displayEmailContent(html) {
    var container = document.getElementById("MailContent");
    container.innerHTML = resolveCidReferences(html);
}

function resolveCidReferences(html) {
    // Use a regular expression to find and replace cid: references with base64-encoded image data
    var resolvedHtml = html.replace(/<img[^>]+src="cid:([^\s'"]+)"[^>]*>/g, function (match, cid) {
        // Replace the cid reference with the URL provided by Outlook
        return '<img src="https://attachment.outlook.live.net/owa/...your_cropped_url_here..." alt="Inline Image">';
    });

    return resolvedHtml;
}
tried this but not worked
Posted
Comments
Andre Oosthuizen 17-Nov-23 9:25am    
Tons of AI generated code that does not work as expected, what else can be expected by copying generated code and hope it will work.

The correct method is to write your own, use AI to help point you in the right direction and I promise that it will probably work as expected AND you will know exactly what each line of code is supposed to do in your app.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900