Home > Back-end >  how to import file html using javascript
how to import file html using javascript

Time:11-19

Javascript / Node.js importing html file

I'm making a node.js server which sends emails on demand. The variable "output" is what I want to send via email. When I use inline html it works fine, however I want to import a complete html file instead.

const { EmailClient } = require("@azure/communication-email");

const connectionString = "<ACS_CONNECTION_STRING>";
const sender = "<SENDER_EMAIL>";
const toRecipients = {
    to: [
        { email: "<[email protected]>", displayName: "Alice" },
    ],
};

const client = new EmailClient(connectionString);
const emailContent = {
    subject: "Send email plain text - JS sample",
  plainText: "",
  // html: "<h3>Hi, this works</h3>", // WORKS
  // html: "<object type="text/html" data="file.html"></object>", // // Doesn't work
  html: "<link href="file.html" rel="import" />", // // Doesn't work
};

async function main() {
  try {
    const emailMessage = {
      sender: sender,
      content: emailContent,
      importance: 'low',
      recipients: toRecipients,
    };

    const sendResult = await client.send(emailMessage);

    if (sendResult && sendResult.messageId) {
        const messageId = sendResult.messageId;     
        if (messageId === null || messageId === undefined) {
        console.log("Message Id not found.");
        return;
      }

      console.log("Send email success, MessageId :", messageId);

      let counter = 0;
      const statusInterval = setInterval(async function () {
        counter  ;
        try {
          const sendStatusResult = await client.getSendStatus(messageId);
            if (sendStatusResult) {
                console.log(`Email status for {${messageId}} : [${sendStatusResult.status}]`);
                if (sendStatusResult.status.toLowerCase() !== "queued" || counter > 12) {
              clearInterval(statusInterval);
            }
          }
        } catch (e) {
          console.log("Error in checking send mail status: ",e);
        }
      }, 5000);
    } else {
      console.error("Something went wrong when trying to send this email: ", sendResult);
    }
  } catch (e) {
      console.log("################### Exception occurred while sending email #####################", e);
  }
}

main();

Help is much appreciated.

CodePudding user response:

You can use fs.readFileSync to import your HTML file as a string.

const emailContent = {
  ...
  html: fs.readFileSync('./file.html', 'utf8'),
  ...
}
  • Related