'Getting error "The attachment content must be base64 encoded" while sending pdf in zip as an attachment using SendGrid

We are using SendGrid latest available Java API to send emails. We are attaching a PDF enclosed in a zip file.

While sending mail we are getting a 404 response code and error message stating "The attachment content must be base64 encoded"

Complete Error Message:

{"errors":\[{"message":"The attachment content must be base64 encoded.","field":"attachments.0.content","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.attachments.content"}\]}

What are we doing wrong? How can we solve this issue and send this attachment? Here is the code where we try to send the PDF in a Zip.

Code:

Path file = Paths.get(this.file.getAbsolutePath());
Attachments attachments = new Attachments();
attachments.setFilename(Base64.getMimeEncoder().encodeToString(file.getFileName().toString().getBytes(StandardCharsets.UTF_8)));
//attachments.setType``("application/pdf");
attachments.setDisposition("attachment");
byte[] attachmentContentBytes = Files.readAllBytes(file);
String attachmentContent = Base64.getMimeEncoder().encodeToString(attachmentContentBytes);
attachments.setContent(attachmentContent);
mail.addAttachments(attachments);

com.sendgrid.SendGrid sg = new com.sendgrid.SendGrid(this.apiKey);
Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);

Response:

{"errors":\[{"message":"The attachment content must be base64 encoded.","field":"attachments.0.content","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.attachments.content"}\]}

Maven dependencies:

  • com.sendgrid.sendgrid-java 4.9.1


Solution 1:[1]

Try Base64.getEncoder() instead of Base64.getMimeEncoder(). Sometimes Sendgrid does not recognize the result from getMimeEncoder().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 E Do