Search code examples
javaspring-bootmime-message

MimeMessage email wont send with attachments


So I have an email template that sends a form perfectly without attachments. Been trying to add the attachments (grab them from the server where they are temporarily stored in a folder) to the form to be emailed as well.

I am working with a Mail.java class, an emailService.java class, and the form's controller to get this functioning.

I am getting a vague error "java null pointer exception". Any idea why my message wont send? I think it has to do with the fileSystemResource addition to the code. But in my console, it shows the files...

Email Service Code:

@Service
public class EmailService {

    private JavaMailSender javaMailSender;

    @Autowired
    public EmailService(JavaMailSender javaMailSender){
        this.javaMailSender = javaMailSender;
    }

    @Autowired
    public StorageService storage;
    @Autowired
    private SpringTemplateEngine templateEngine;

    public void sendSimpleMessage(Mail mail, DirectBind directBind) throws MessagingException, IOException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,
                MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                StandardCharsets.UTF_8.name());

        helper.addAttachment("Mail_Icon.png", new ClassPathResource("static/images/Mail_Icon.png"));

        Context context = new Context();
        context.setVariables(mail.getModel());
        context.setVariable("directBind",directBind);
        String html = templateEngine.process("emailMessage", context);

        helper.setTo(mail.getTo());
        helper.setText(html, true);
        helper.setSubject(mail.getSubject());
        helper.setFrom(mail.getFrom());

//        List<Object> files = new ArrayList<>();
//        files.add(storage.getUploadDir());

        FileSystemResource allFiles= new FileSystemResource(new File(storage.getUploadDir()));
        helper.addAttachment(allFiles.getFilename(),allFiles);

        javaMailSender.send(message);
    }
}

Send Function in controller:

@RequestMapping(value="/directBind",  params="send")
    public String send(Model model, @ModelAttribute(value="directBind") DirectBind directBind){
        List<String> businessAgencyList = directBind.getBusinessAgencyList();
        Mail mail = new Mail();
        mail.setFrom("[email protected]");
        mail.setTo(new String[]{"[email protected]"});
        mail.setSubject("Oli Affiliate - AMS360 & PMA Data Checklist");

        Map<String, Object> mailModel = new HashMap<String, Object>();
        mail.setModel(mailModel);

       // List<Object> files = new ArrayList<>();
       // files.add(storageService.getUploadDir());
       // mail.setAttachments(files);

        try {
            emailService.sendSimpleMessage(mail, directBind);
        } catch (Exception e) {
            e.printStackTrace();
            return ("redirect:/?sentMessageFail");
        }
        return ("redirect:/?sentMessage");
    }

    @RequestMapping(value="/email")
    public String email(){
        return "emailMessage";
    }
}

My Mail Model:

public class Mail {

    private String from;
    private String[] to;
    private String subject;
    private List<Object> attachments;
    private Map<String, Object> model;

    public Mail() {

    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String[] getTo() {
        return to;
    }

    public void setTo(String[] to) {
        this.to = to;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public List<Object> getAttachments() {
        return attachments;
    }

    public void setAttachments(List<Object> attachments) {
        this.attachments = attachments;
    }


    public Map<String, Object> getModel() {
        return model;
    }

    public void setModel(Map<String, Object> model) {
        this.model = model;
    }

}

Error Message...

org.springframework.mail.MailSendException: Failed messages: java.lang.NullPointerException; message exception details (1) are:
Failed message 1:
java.lang.NullPointerException
	at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:226)
	at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:299)
	at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1375)...


Solution

  • I would add it as a comment if I could (rep is below 50).

    You might try to replace

    helper.addAttachment(allFiles.getFilename(),allFiles);
    

    with

    helper.addAttachment(allFiles.getFilename(),allFiles.getFile());
    

    Edit:

    FileSystemResource allFiles= new FileSystemResource(new File(storage.getUploadDir() + "/filename.txt"));
    

    Iterate through files (might need adjustments):

    File myDir = new File(storage.getUploadDir());
    File[] myFiles = myDir.listFiles();
    
    if (myFiles != null) {
        for (File cFile : myFiles) {
            helper.addAttachment(cFile.getName(), cFile);
        }
    }