Search code examples
javaspring-bootmailjet

How to send attachment through Mailjet in JAVA


I want to send mail with an attachment through Mailjet in java. I have no problem while sending simple mail without attachment but when I try to add attachment I am getting this error:

400
[{"ErrorIdentifier":"314408e7-e528-469f-9361-2eb3c24b2b32","ErrorCode":"mj-0004","ErrorRelatedTo":["Messages.Attachments"],"ErrorMessage":"Type mismatch. Expected type \"Attachments\".","StatusCode":400}]

And my code looks like this:

@Service
public class MailJetSenderImp implements MailJetSender {

    Message message = new Message();

    @Override
    public ResponseEntity<Message> sendMail(String To, String Body, String Subject, File attachment) throws MailjetSocketTimeoutException, JSONException, IOException {

        FileInputStream fileInputStream = new FileInputStream(attachment);
        int byteLength=(int) attachment.length(); //bytecount of the file-content
        byte[] filecontent = new byte[byteLength];
        fileInputStream.read(filecontent,0,byteLength);
        byte[] encoded = Base64.getEncoder().encode(filecontent);


        MailjetRequest email = new MailjetRequest(Emailv31.resource)

                .property(Emailv31.MESSAGES, new JSONArray()
                        .put(new JSONObject()
                                .put(Emailv31.Message.FROM, new JSONObject()
                                        .put("Email","[email protected]" )
                                        .put("Name", "xxxxx"))
                                .put(Emailv31.Message.TO, new JSONArray()
                                        .put(new JSONObject()
                                                .put("Email", To)))
                                .put(Emailv31.Message.SUBJECT, Subject)
                                .put(Emailv31.Message.TEXTPART, "")
                                .put(Emailv31.Message.HTMLPART, Body)
                                    .put(Emailv31.Message.ATTACHMENTS,encoded)));

        final String mailjetApiKey = "xxxxxxxx";
        final String mailjetSecretKey = "yyyyyyyy";

        MailjetClient client = new MailjetClient(
                mailjetApiKey, mailjetSecretKey, new ClientOptions("v3.1"));


        try {
            // trigger the API call
            MailjetResponse response = client.post(email);
            // Read the response data and status
            System.out.println(response.getStatus());
            System.out.println(response.getData());
            message.setCode(response.getStatus());
            message.setMessage(response.getData().toString());
            return ResponseEntity.status(HttpStatus.OK).body(message);
        } catch (MailjetException e) {
            System.out.println("Mailjet Exception: " + e);
            message.setCode(400);
            message.setMessage("could not send email");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message);

        }
    }
}

I get error message on (.put(Emailv31.Message.ATTACHMENTS,encoded)));


Solution

  • Here is the Java code to send the mail attachment

    The ATTACHMENTS data is a JSON array containing 3 fields:

    1. ContentType - Content type of the attachment

    2. Filename - name of the file attachment that the receiver would see

    3. Base64Content - Base64 encoded file data as String

    So, encode the file content as String ( I used the Base64 encoder from mailjet client JAR itself here ). filecontent is the byte[]. A hardcoded PDF file code sample below :

        java.nio.file.Path pdfPath = 
             java.nio.file.Paths.get("c:\\D\\sample.pdf");
        byte[] filecontent = java.nio.file.Files.readAllBytes(pdfPath);
        String fileData = com.mailjet.client.Base64.encode(filecontent);
    

    Next, use this code to send the attachment, your other code remains same. Example here is for a PDF file, choose your MIME type correctly

      .put(Emailv31.Message.ATTACHMENTS,
                new JSONArray().put(new JSONObject().put("ContentType", "application/pdf")
                               .put("Filename", "abc.pdf")
                               .put("Base64Content", fileData)))
     .put(Emailv31.Message.HTMLPART,...