0

I'm trying to send an email with PHP 7.1 via cURL. I receive the email but it doesn't have the subject, body (it's empty) and in "to" field I get "undisclosed recipients". Am I missing any parameters inside curl_setopt_array?

$postData = ["from" => John Doe,
             "body" => "this is a test",
             "to" => "xxxxxxxx@yyyyy.zzz",
             "subject" => A simple test,
];
$ch = curl_init();
curl_setopt_array($ch, [
     CURLOPT_URL => 'smtp.mydomain.com:25/mydomain.com',
     CURLOPT_MAIL_FROM => '<no-reply@mydomain.com>',
     CURLOPT_MAIL_RCPT => ['xxxxxxxx@yyyyy.zzz'],
     CURLOPT_HTTPHEADER => array(
         "Accept: application/json",
         "Content-Type: application/json"
      ),
     curl_setopt($ch, CURLOPT_POST, true),
     CURLOPT_POSTFIELDS => json_encode($postData),
     CURLOPT_UPLOAD => true,
]);

curl_exec($ch);
curl_close($ch);
splunk
  • 6,435
  • 17
  • 58
  • 105

1 Answers1

1

Your code is a bit all over the place; I assume since you said you were able to send an email that these are just copy/paste errors.

I'm not sure why you're JSON-encoding all the headers, or why you're including the body in with the headers. From the very few examples I've seen of using cURL for email, you'll want to put the mail headers and body into the POST data like this:

$maildata = <<< EOF
From: John Doe <no-reply@my.domain.example.com>
To: xxxxxxxx@yyyyy.zzz
Subject: A simple test

this is a test
EOF;

$ch = curl_init();
curl_setopt_array($ch, [
     CURLOPT_URL => 'smtp://my.mailserver.com/my.domain.example.com',
     CURLOPT_MAIL_FROM => 'John Doe <no-reply@my.domain.example.com>',
     CURLOPT_MAIL_RCPT => ['xxxxxxxx@yyyyy.zzz'],
     CURLOPT_POST => true,
     CURLOPT_POSTFIELDS => $maildata,
     CURLOPT_UPLOAD => true,
]);

curl_exec($ch);
curl_close($ch);

Note that the CURLOPT constants you're using weren't introduced until PHP 7.2, so you will need to upgrade. PHP 7.1 has been EOL for a while now, so I'm sure you were planning to update anyway.

That said, you'd be better served by using more common approaches such as PHPMailer or SwiftMailer. Considering you're using constants and functionality that aren't even mentioned in the PHP documentation, you're unlikely to find a lot of other people trying this.

miken32
  • 42,008
  • 16
  • 111
  • 154