Perl Requires Chilkat v11.0.0+
Perl
SendGrid: Save and verify a topic opt-out
See more SendGrid Examples
Use this when a signed-in reader turns off Product updates. Look up the configured group before submitting: SendGrid warns that a nonexistent or deleted group can cause a global suppression instead. Keep the group active while processing preferences. Deleting a marketing contact is not a substitute for recording an opt-out.
Add group suppressions ยท Check specific addresses
Chilkat Perl Downloads
use strict;
use warnings;
use Chilkat2;
# Assumes Chilkat is unlocked. See Global Unlock Sample.
my $success = 0;
my $http = Chilkat2::Http->new;
$http->RequireSslCertVerify(1);
# Supply your API key from protected configuration; AuthToken adds the Bearer prefix.
$http->AuthToken('SENDGRID_API_KEY');
my $resp = Chilkat2::HttpResponse->new;
# Take the address from the authenticated account and the group ID from configuration.
my $address = 'reader@example.com';
$http->SetUrlVar('group', '12345');
$success = $http->HttpNoBody('GET', 'https://api.sendgrid.com/v3/asm/groups/{$group}', $resp);
if (!$success) {
if ($resp->StatusCode == 0) {
print $http->LastErrorText, "\n";
} else {
print 'HTTP ', $resp->StatusCode, ': ', $resp->BodyStr, "\n";
}
exit;
}
if ($resp->StatusCode != 200) {
print 'HTTP ', $resp->StatusCode, ': ', $resp->BodyStr, "\n";
exit;
}
my $groupInfo = Chilkat2::JsonObject->new;
$success = $groupInfo->Load($resp->BodyStr);
if (!$success) {
print "Unexpected response: expected JSON.\n";
exit;
}
if (!$groupInfo->StringOfEquals('name', 'Product updates', 1)) {
print "Unexpected unsubscribe group; no preference was changed.\n";
exit;
}
my $addresses = Chilkat2::JsonObject->new;
$addresses->UpdateString('recipient_emails[0]', $address);
$success = $http->HttpJson('POST', 'https://api.sendgrid.com/v3/asm/groups/{$group}/suppressions', $addresses, 'application/json', $resp);
if (!$success) {
if ($resp->StatusCode == 0) {
print $http->LastErrorText, "\n";
} else {
print 'HTTP ', $resp->StatusCode, ': ', $resp->BodyStr, "\n";
}
exit;
}
if ($resp->StatusCode != 201) {
print 'HTTP ', $resp->StatusCode, ': ', $resp->BodyStr, "\n";
exit;
}
$success = $http->HttpJson('POST', 'https://api.sendgrid.com/v3/asm/groups/{$group}/suppressions/search', $addresses, 'application/json', $resp);
if (!$success) {
if ($resp->StatusCode == 0) {
print $http->LastErrorText, "\n";
} else {
print 'HTTP ', $resp->StatusCode, ': ', $resp->BodyStr, "\n";
}
exit;
}
if ($resp->StatusCode != 200) {
print 'HTTP ', $resp->StatusCode, ': ', $resp->BodyStr, "\n";
exit;
}
my $matches = Chilkat2::JsonArray->new;
$success = $matches->Load($resp->BodyStr);
if (!$success) {
print "Unexpected response: expected JSON.\n";
exit;
}
if ($matches->Size == 1) {
print 'Confirmed opt-out: ', $matches->StringAt(0), "\n";
} else {
print "Opt-out not confirmed. Recheck this group.\n";
}