javascriptcloudflare-workerssparkpost

Content.text must be string error - using Sparkpost Api from Cloudflare worker


I am using Cloudflare worker to accept a post request and mail it then using Spark post Api. I am getting content.text must be a string error when I send it to Api.

async function sendEmail(request, SPARKPOST_API_KEY) {
    const jsonData = await request.json();
    const city = jsonData.city;
    const state = jsonData.state;
    const message = city + "," + state;

    const body = JSON.stringify({
      options: {
        sandbox: false,
      },
      content: {
        from: FROM_EMAIL,
        subject: 'Data Submission',
        text: message
      },
      recipients: [{ address: TO_EMAIL }],
    });

If I do the following the mail gets send without any issue.

content: {
        from: FROM_EMAIL,
        subject: 'Data Submission',
        text: "Hello World"
      },

Also, I tried doing the following.

const message = "<p>${city}<p>";
const body = JSON.stringify({
      options: {
        sandbox: false,
      },
      content: {
        from: FROM_EMAIL,
        subject: 'Data Submission',
        html: message
      },
      recipients: [{ address: TO_EMAIL }],
 });

But then I would get content.html must be a string. Also is there any way I can send city and state so they each appear on a new line.


Solution

  • For anyone facing a similar issue in the future, formatting like this worked for me.

    body = JSON.stringify({
          options: {
            sandbox: false,
          },
          content: {
            from: FROM_EMAIL,
            subject: "New Student Application",
            html: `<div><p>Student Name: ${jsonData.studentName}</p><p>Gender: ${jsonData.gender}</p><p>Contact No: ${jsonData.contactNumber}</p></div>`,
          },
          recipients: [{ address: TO_EMAIL }],
        });