Sending email in HTML format via an Ajax JS request to an API that uses Curl in PHP

Asked

Viewed 68 times

0

Good afternoon to all!

I am structuring a contact form for a website and am using an API from sendgrid, available via rapidapi (https://rapidprod-sendgrid-v1.p.rapidapi.com/mail/send).

With this, we have this structure in javascript:

some code...

 let url = window.location.href,
      host = window.location.host,
      content = "";

    let wrap =
        'style="max-width: 100%;margin: 0 auto;font-family:Roboto,Google Sans,Helvetica,Arial,sans-serif;"',
      card =
        'style="border:1px solid #dedede;border-radius:20px;overflow:hidden"',
      header = 'style="padding:15px;background: #fff;text-align: center;"',
      info =
        'style="padding: 50px 30px;font-size:16px;border-top:1px solid #ddd"',
      title =
        'style="text-align: center; color:#3c3c3b;font-size: 30px;font-weight: 800;margin: 20px 0 40px 0;font-family: Google Sans,Roboto,Helvetica,Arial,sans-serif;"',
      subtitle =
        'style="text-align: center; font-weight: 200;margin-top: 40px;"',
      footer =
        'style="text-align: center; margin-top: 30px;font-size: 13px;text-align:center;color: #666767"',
      year = new Date().getFullYear(),
      linkColor = 'style="color: #2f2e2e;text-decoration:none"';
    content = `
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <div ${wrap}>
      <div ${card}>
        <div>
          <div ${header}>
            <a target="_BLANK" href="https://mikhaelangelo.com.br/">
              <img src="https://mikhaelangelo.com.br/wp-content/themes/mikhaelangelo/img/michel_icon_500.png" style="width:38px;height: auto;">
            </a>
          </div>

          <div ${info}>
            <h2 ${title}>Mikhaelangelo</h2>
            <h2 ${subtitle}>Informações recebidas</h2>
            <p><b>Nome:</b></p><p>${name}</p>
            <p><b>E-mail:</b></p><p>${email}</p>
            <p><b>Assunto:</b></p><p>${subject}</p>
            <p style="margin-bottom:0!important"><b>Mensagem:</b></p><p>${message}</p>
          </div>
        </div>
      </div>

      <div ${footer}>
        <p>E-mail recebido através da página do site: <a href="${url}" target="_blank" ${linkColor}>${host}</a>.</p>
        <p>&copy; ${year} Mikhaelangelo.</p>
      </div>
    </div>
  </body>
</html>`;

    let dados = {
      request: "Mikhaelangelo",
      from: email,
      to: "[email protected]",
      subject: subject,
      message: content,
    };

    var settings = {
      url: "contact_form/contact_form.php",
      method: "POST",
      async: false,
      crossDomain: true,
      processData: true,
      data: dados,
    };

    $.ajax(settings).success(function (response) {
      let data = JSON.parse(response);
      console.log(data);
      console.log(response);
      if (data.success) {

...restante do código

and contact_form.php that receives the Ajax request:

<?php
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://rapidprod-sendgrid-v1.p.rapidapi.com/mail/send",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "
    {
    \"personalizations\": 
    [
        {
            \"to\": 
            [
                {
                    \"email\": \"[email protected]\"
                }
            ],
            \"subject\": \"$subject\"
        }
    ],
    \"from\": 
    {
        \"email\": \"$from\"
    },
    \"content\": 
    [
        {
            \"type\": \"text/plain\",
            \"value\": \"$message\"
        },
        {
            \"type\": \"text/html\",
            \"value\": \"$message\"
        }
    ]
}",
    CURLOPT_HTTPHEADER => array(
        "accept: application/json",
        "content-type: application/json",
        "x-rapidapi-host: rapidprod-sendgrid-v1.p.rapidapi.com",
        "x-rapidapi-key: ****************"
    ),
));

$response = curl_exec($curl);
$response = json_encode($response);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

I’m having trouble sending the email in HTML format. the API server returns me:

{"errors":[{"message":"Bad Request","field":null,"help":null}]}

I don’t know if it could be related to the quotes in the HTML code or something.

2 answers

1


That reply should be a comment but I have no reputation for it. Can’t you access the variables sent by ajax? Something like this

$email = $_POST['dados']['personalizations']['to']['email];
  • I can’t. I tried to do this but when I add a variable in this code, it returns me "Unexpected token < in JSON at position 0" this "<" is a piece of JSON HTML code. If I remove this variable statement, the code "works". Strange, right?

  • You declared the variable within the function curl_setopt_array? If yes, try to declare out.

  • I declared her out. Just below the curl_init();

  • tries to delete Curl code, see if you can access the variable that came by the post and see if everything "ok" with it

  • deleted everything, left only $email = $_POST['data']['personalizations']['to']['email']; echo $email; and continues the "Unexpected token < in JSON at position 0" I think it can be in in the ajax call

  • Take the crossdomain and see if you can access the variables. If you still can’t, check the url to see if you’re taking the path you want

  • 1

    I am able to access the variables and feed in the content of the email! However, my challenge now is just one: to be able to fix the large string that is the HTML format of the message. I’m getting a response from the api server: "{"errors":[{"message":"Bad Request","field":null,"help":null}]}" I’m editing this topic to update

Show 2 more comments

1

Problem solved!!

I put all the html code that corresponds to the body of the message in:

    \"content\": 
    [
        {
            \"type\": \"text/html\",
            \"value\": HTML AQUI
        }
    ]

But I put it as a string, no spaces. guy:

<html><head><meta name='viewport' content='width=device-width, initial-scale=1.0'></head><body><div style='max-width: 100%;margin: 0 auto;font-family:Roboto,Google Sans,Helvetica,Arial,sans-serif;'><div style='border:1px solid #dedede;border-radius:20px;overflow:hidden;'><div><div style='padding:15px;background: #fff;text-align: center;'><a target='_BLANK' href='https://mikhaelangelo.com.br/'><img...</html>

and it was!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.