如何使用 PHP 通过 ZOHO api 发送电子邮件?

Mar*_* AJ 6 php email api rest zoho

我已经关注了这个文档,这是我的代码:

$url = "https://mail.zoho.com/api/accounts/662704xxx/messages";
$param = [  "fromAddress"=> "myemail@mydomain.com",
            "toAddress"=> "somewhere@gmail.com",
            "ccAddress"=> "",
            "bccAddress"=> "",
            "subject"=> "Email - Always and Forever",
            "content"=> "Email can never be dead ..."];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
die;
Run Code Online (Sandbox Code Playgroud)

回应是:

{"data":{"errorCode":"INVALID_TICKET","moreInfo":"Invalid ticket"},"status":{"code":400,"description":"Invalid Input"}}
Run Code Online (Sandbox Code Playgroud)

并且响应意味着:(根据this

BAD REQUEST - 请求 API 中传递的输入无效或不正确。请求者必须更改输入参数并再次发送请求。

知道我该如何解决吗?

ish*_*egg 5

为了通过 Zoho 的 API 发送邮件,您需要首先进行身份验证,如APIDocs 所示

注意:您可以使用此处的 API检索当前已验证用户的 accountid。

也就是说,参考您的评论,您不需要在服务器上安装 SMTP 服务器即可使用 PHPMailer 发送邮件:

集成 SMTP 支持 - 无需本地邮件服务器即可发送

来源

Zoho 要求您使用 TLS 和 587 端口,因此您可以像这样设置连接:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

$phpMailer = new PHPMailer(true);
$phpMailer->SMTPDebug = SMTP::DEBUG_SERVER;
$phpMailer->isSMTP();
$phpMailer->Host = "smtp.zoho.com";
$phpMailer->SMTPAuth = true;
$phpMailer->Username = "your-user";
$phpMailer->Password = "your-password";
$phpMailer->SMTPSecure = "tls"; // or PHPMailer::ENCRYPTION_STARTTLS
$phpMailer->Port = 587;
$phpMailer->isHTML(true);
$phpMailer->CharSet = "UTF-8";
$phpMailer->setFrom("mail-user", "mail-name");

$phpMailer->addAddress("mail-to");
$phpMailer->Subject = "subject";
$phpMailer->Body = "mail-body";
$phpMailer->send();
Run Code Online (Sandbox Code Playgroud)