尝试使用Sendgrid API创建自定义联系表单,将收件人添加到联系人列表,按照https://github.com/sendgrid/sendgrid-php/blob/master/examples/contactdb/contactdb.php中的示例,目前我有:
require("sendgrid-php.php");
// Send an Email
$from = new SendGrid\Email(null, "info@test.com");
$subject = "Hello World from the SendGrid PHP Library!";
$to = new SendGrid\Email(null, "my@email.com");
$content = new SendGrid\Content("text/plain", "Hello, Email!");
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$apiKey = 'API_GOES_HERE';
$sg = new \SendGrid($apiKey);
$list_id = "12345";
$recipient_id = base64_encode("test@email.com");
$listResponse = $sg->client->contactdb()->lists()->_($list_id)->recipients()->_($recipient_id)->post();
echo $listResponse->statusCode();
echo $listResponse->body();
echo $listResponse->headers();
但我收到了错误:
**message":"Recipient ID does not exist"**
答案 0 :(得分:0)
所以文档没有说的是用户必须先在SendGrid中存在才能添加到联系人列表中。
所以步骤是:
这是我的工作代码,以防任何人需要它,这样你就不会像我一样花费数小时了:
// Get SendGrid credentials
require("sendgrid-php.php");
$apiKey = 'YOUR_API_KEY';
$sg = new \SendGrid($apiKey);
// Only process POST requests
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get the form fields and remove whitespace
$array[0]['first_name'] = strip_tags(trim($_POST['first-name']));
$array[0]['last_name'] = strip_tags(trim($_POST['last-name']));
$array[0]['email'] = filter_var(trim($_POST['user-email']), FILTER_SANITIZE_EMAIL);
$firstName = strip_tags(trim($_POST['first-name']));
$lastName = strip_tags(trim($_POST['last-name']));
$recipient = filter_var(trim($_POST['user-email']), FILTER_SANITIZE_EMAIL);
// Create the recipient in SendGrid (part I was missing)
$recipientResponse = $sg->client->contactdb()->recipients()->post($array);
// Build the email
$from = new SendGrid\Email('Company Name', "example@company.com");
$subject = "Subject";
$to = new SendGrid\Email(null, $recipient);
$content = new SendGrid\Content("text/html", YOUR HTML TEMPLATE CODE HERE);
$mail = new SendGrid\Mail($from, $subject, $to, $content);
// Send the email
$emailResponse = $sg->client->mail()->send()->post($mail);
// And finally add recipient to a contact list
$list_id = "123456";
$recipient_id = base64_encode($recipient);
$listResponse = $sg->client->contactdb()->lists()->_($list_id)->recipients()->_($recipient_id)->post($request_body);