Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

SendGrid: Send product updates with a topic unsubscribe link

See more SendGrid Examples

Use the numeric ID of your existing Product updates unsubscribe group and a verified sender. The ASM tag expands to the recipient-specific link for this group. A click opts the recipient out of this topic; a global unsubscribe applies across topics.

Unsubscribe tags ยท Mail Send

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean success = false;

        // Assumes Chilkat is unlocked. See Global Unlock Sample.
        success = false;
        Http http = new Http();
        http.setRequireSslCertVerify(true);
        // Supply your API key from protected configuration; AuthToken adds the Bearer prefix.
        http.setAuthToken("SENDGRID_API_KEY");
        HttpResponse resp = new HttpResponse();

        JsonObject message = new JsonObject();
        message.updateString("from.email", "sender@example.com");
        message.updateString("personalizations[0].to[0].email", "recipient@example.com");
        message.updateInt("asm.group_id", 12345);
        message.updateString("subject", "Product updates: November edition");
        message.updateString("content[0].type", "text/html");
        message.updateString("content[0].value", "<p>The new catalog is available.</p><p><a href=\"<%asm_group_unsubscribe_raw_url%>\">Unsubscribe from product updates</a></p>");

        try {
            http.httpJson("POST", "https://api.sendgrid.com/v3/mail/send", message, "application/json", resp);
        } catch (ChilkatException e) {
            if (resp.getStatusCode() == 0) {
                System.out.println(e.getLastErrorText());
            } else {
                System.out.println("HTTP " + resp.getStatusCode() + ": " + resp.getBodyStr());
            }

            return;
        }

        if (resp.getStatusCode() != 202) {
            System.out.println("HTTP " + resp.getStatusCode() + ": " + resp.getBodyStr());
            return;
        }

        System.out.println("Accepted for delivery (HTTP 202).");
    }
}