4

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("no-reply@hgitservices.com");
        mail.setTo(new String[]{"stacief@hgitservices.com"});
        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)...
Stacie
  • 306
  • 7
  • 26
  • 1
    Just an FYI - your stack trace doesn't actually illustrate what the actual problem is. It's literally an array of stack trace elements. Without that the stack trace is tacitly useless and should be updated with the actual error message. – Makoto Nov 28 '18 at 20:07
  • Hmm, I feel like my error message and my stack trace are really vague and unhelpful which is what lead me to ask here. But then again, fairly new to Java (3mo) and I'm sure I don't actually understand the stack trace. Or how to use the logger functionality really. – Stacie Nov 28 '18 at 21:12
  • Is `new ClassPathResource("static/images/Mail_Icon.png")` returning `null`? – Makoto Nov 28 '18 at 21:26
  • No, that's not throwing the null pointer. The issue came when trying to add the files/addAttachment allFiles portion of the code. I've always had the mail icon img in the code and it was working previously /sending the message with the mail image. – Stacie Nov 28 '18 at 21:31

2 Answers2

1

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);
    }
}
  • This reads like an answer to me. Why would you want to comment in this context? – Makoto Nov 28 '18 at 20:05
  • Because I am just guessing. Got down-voted for that in the past))) – Denis Kovzelyuk Nov 28 '18 at 20:06
  • You subject yourself to criticism for guesses. If you don't know it may be better to not answer. If you feel somewhat confident in your answer then roll with it. – Makoto Nov 28 '18 at 20:08
  • @DenisKovzelyuk didn't work, but thanks for the thought! – Stacie Nov 28 '18 at 21:01
  • I feel like @DenisKovzelyuk is on the right track here... think that it's pulling and saving the path as the attachment instead of the actual files stored in the folder path... any other ideas how to grab the files? – Stacie Nov 28 '18 at 21:41
  • 1
    @Stacie Have you tried FileSystemResource allFiles= new FileSystemResource(new File(storage.getUploadDir() + "/filename.txt")); If it works, you can loop through the each file in directory and create new attachment – Denis Kovzelyuk Nov 28 '18 at 22:15
  • @DenisKovzelyuk it works to grab it that way since I am specifically calling the file by name. Unfortunately I need it to be dynmaic because I won't know what the filenames of uploaded files will be. – Stacie Nov 29 '18 at 18:09
  • Yes!! I just figured it out as well, thank you so much, your answer is the answer I was looking for! Thanks @DenisKovzelyuk . Just to clarify for anyone else using this, did not need FileSystemResource line at all, just an array and for loop to iterate through. – Stacie Nov 29 '18 at 18:48
0

You need to use:

  @Override
    public void sendAttachmentMessage(List<String> to, String subject, String text, String pathToAttachment) {

    MimeMessage message = emailSender.createMimeMessage();

    MimeMessageHelper helper = null;
    try {
        helper = new MimeMessageHelper(message, true);

        helper.setTo(to.toArray(new String[to.size()]));
        helper.setSubject(subject);

        String content = builder.build(text);
        helper.setText(content, true);

        FileSystemResource file = new FileSystemResource(new File(pathToAttachment));

        helper.addAttachment(file.getFilename(), file);
    } catch (MessagingException e) {
        LOG.error("Error sending email with attachment.", e);
    }

    emailSender.send(message);
    }
ACV
  • 9,964
  • 5
  • 76
  • 81