简体   繁体   English

email 中的空字段通过 cURL 和 PHP 发送

[英]empty fields in email sent via cURL with PHP

I'm trying to send an email with PHP 7.1 via cURL.我正在尝试通过 cURL 发送带有 PHP 7.1 的 email。 I receive the email but it doesn't have the subject, body (it's empty) and in "to" field I get "undisclosed recipients".我收到 email 但它没有主题、正文(它是空的)并且在“收件人”字段中我得到“未公开的收件人”。 Am I missing any parameters inside curl_setopt_array?我是否缺少 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);

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.我假设既然你说你能够发送 email 这些只是复制/粘贴错误。

I'm not sure why you're JSON-encoding all the headers, or why you're including the body in with the headers.我不确定您为什么要对所有标头进行 JSON 编码,或者为什么要将正文包含在标头中。 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:从我看到的使用 cURL 为 email 的极少数示例中,您需要将邮件标题和正文放入 POST 数据中,如下所示:

$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.请注意, 您使用的CURLOPT常量直到 PHP 7.2 才引入,因此您需要升级。 PHP 7.1 has been EOL for a while now, so I'm sure you were planning to update anyway. PHP 7.1 已经 EOL 一段时间了,所以我确定您无论如何都打算更新。

That said, you'd be better served by using more common approaches such as PHPMailer or SwiftMailer.也就是说,使用 PHPMailer 或 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.考虑到您正在使用 PHP 文档中甚至没有提到的常量和功能,您不太可能找到很多其他人在尝试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM