sendgrid / sendgrid-java

The Official Twilio SendGrid Led, Community Driven Java API Library
https://sendgrid.com
MIT License
486 stars 408 forks source link

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

Open surajintellicus opened 2 years ago

surajintellicus commented 2 years ago

We are using SendGrid latest JAVA API's available to send emails. As part of attachment we are attaching a pdf enclosed in a zip file. While sending mail we are getting 404 as 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"}]}_

Wanted help if we are doing anything wrong and need more clarity how can we solve this issue. Please find attached code snippet.

Code Snippet :

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);

Error :

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"}]}_

Using Maven Repo :

com.sendgrid sendgrid-java 4.9.1

Sheet 1(1).zip