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

SendGrid: Attach a PDF invoice to an email

See more SendGrid Examples

Read invoice.pdf from the working directory and send it as a downloadable file named invoice-1042.pdf. SendGrid expects Base64 file content in the JSON request, not a path or a multipart upload. The whole message, including attachments, must be under 30 MB; allow for Base64 to add about a third to the file size.

Use an API key with Mail Send permission and a verified sender identity. Replace the example addresses before sending.

SendGrid documentation: Mail Send size limits.

Chilkat CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    CkHttp http = new CkHttp();
    http.put_RequireSslCertVerify(true);
    //  Supply a Mail Send API key from your application configuration. AuthToken adds the Bearer prefix.
    http.put_AuthToken("SENDGRID_API_KEY");

    CkJsonObject message = new CkJsonObject();
    //  Replace the sender with a verified sender identity and the recipient with your destination.
    message.UpdateString("from.email","sender@example.com");
    message.UpdateString("personalizations[0].to[0].email","recipient@example.com");
    message.UpdateString("subject","Invoice 1042");
    message.UpdateString("content[0].type","text/plain");
    message.UpdateString("content[0].value","Your invoice is attached as invoice-1042.pdf.");

    CkBinData fileData = new CkBinData();
    boolean loaded = fileData.LoadFile("invoice.pdf");
    if (loaded != true) {
        System.out.println("Could not read invoice.pdf. Check the path and file permissions.");
        return;
        }

    if (fileData.get_NumBytes() == 0) {
        System.out.println("invoice.pdf is empty.");
        return;
        }

    //  Encode the file bytes once. The content field contains only Base64, without a data URI prefix.
    message.UpdateString("attachments[0].content",fileData.getEncoded("base64"));
    message.UpdateString("attachments[0].type","application/pdf");
    message.UpdateString("attachments[0].filename","invoice-1042.pdf");
    message.UpdateString("attachments[0].disposition","attachment");

    CkHttpResponse response = new CkHttpResponse();
    http.HttpJson("POST","https://api.sendgrid.com/v3/mail/send",message,"application/json",response);
    //  HttpJson also returns false for HTTP errors. A zero status means no HTTP response arrived.
    if (response.get_StatusCode() == 0) {
        System.out.println(http.lastErrorText());
        return;
        }

    if (response.get_StatusCode() != 202) {
        System.out.println("Mail Send returned HTTP " + response.get_StatusCode());
        //  For validation errors the response body identifies the offending field and explains why.
        System.out.println(response.bodyStr());
        return;
        }

    System.out.println("SendGrid accepted the email for delivery (HTTP 202).");
  }
}