Fatih Doğmuş
Fatih Doğmuş

Reputation: 531

Attachment's are not sent with spring mail

i'm trying to send mails with spring mail's JavaMailSender. i first implemented the version without attachments but now i need to add attachments. but, although the attachments are added to MimeMessageHelper (i can see on debug mod that the parts are adder), the attachments are not sent with mail. mails subject and content are correctly sent to receivers but attachments are missing. below is my code:

    try {
        MimeMessageHelper messageHelper = new MimeMessageHelper(this.mimeMessage,true, CharEncoding.UTF_8);

        for(Mail mails : unsentMails) {
            try {

                /*
                  Here, we first get the list of receivers and main targets according to their type information
                  Then, we add them to messageHelper
                 */
                Set<Attachments> attachments = mails.getFk_attachments();

                for(MailReciever item : mails.getRecievers()) {
                    if(item.getType().equals("cc")) {
                            messageHelper.addCc(item.getAddress());
                        }
                        else {
                            messageHelper.addTo(item.getAddress());
                        }
                }
                for(Attachments file : attachments) {
                    messageHelper.addAttachment(file.getFileName(),
                        new ByteArrayResource(file.getContent()),file.getContentContentType());

                    try {
                        FileUtils.writeByteArrayToFile(new File("C:\\Users\\fatih.dogmus\\Desktop\\deneme\\"+file.getFileName()),file.getContent());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                FileSystemResource fileSystemResource = (new FileSystemResource(new File("C:\\Users\\fatih.dogmus\\Desktop\\hebele.txt\\")));
                messageHelper.addAttachment(fileSystemResource.getFilename(),fileSystemResource  );
                messageHelper.setSubject(mails.getSubject());
                messageHelper.setFrom(this.userName,this.sendingName);

                mimeMessage.setContent(mails.getContent(),"text/html");

                this.javaMailSender.send(this.mimeMessage);
                mails.setStatus(EmailStatus.SUCCEEDED);

                for(MailReciever item : mails.getRecievers()) {
                    item.setStatus(EmailStatus.SUCCEEDED);
                    item.setLastAttemptDate(zonedDateTime);
                }

            }
            catch (MailException mailException) {
                for(MailReciever item : mails.getRecievers()) {
                    item.incrementAttemptCount();
                    item.setStatus(EmailStatus.ENQUEUED);
                }


                mails.incrementAttemptCount();
                mails.setStatus(EmailStatus.ENQUEUED);


                if(mails.getSendingAttempts() == 3) {
                    mails.setStatus(EmailStatus.FAILED);
                    for(MailReciever item : mails.getRecievers()) {
                        item.setStatus(EmailStatus.FAILED);
                        item.setLastAttemptDate(zonedDateTime);
                    }

                    System.out.println("Failed to send mail. Aborting.");
                }
                else {
                    System.out.println(String.format("Attempt count is %d. Will try again", mails.getSendingAttempts()));
                }
                mailException.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } finally {
                mailRepository.save(mails);
                mailRecieverRepository.save(mails.getRecievers());
            }
        }
    }
    catch (MessagingException e) {
        e.printStackTrace();
    }

i get the required data from database like mail itself, receivers and attachment. attachments are stored in databse with clob (aka as byte[]). i also try to add a file from my local system but that doesn't work either. i also try writing the file that is read from database to a file in my system and that seems to work as well so database system is working as intended. saving and retrieving doesn't look like the problem. below is mail mail configuration with .yml file

mail:
        host: smtp.gmail.com
        port: 587
        name: ******
        username: ******
        password: ********         
        protocol: smtp
        tls: true
        properties.mail.smtp:
            auth: true
            starttls.enable: true
            ssl.trust: smtp.gmail.com

name field is just a field to set the name field on the mail from other than mails itself.

Thank you.

Upvotes: 3

Views: 1812

Answers (2)

Tien Do Nam
Tien Do Nam

Reputation: 4440

I got the same problem, as Fatih said, you have to put the text into the helper and not into the mimeMessage.

messageHelper.addAttachment(fileSystemResource.getFilename(),fileSystemResource  );
messageHelper.setSubject(mails.getSubject());
messageHelper.setFrom(this.userName,this.sendingName);

// this is correct
messageHelper.setText(mails.getContent(),true);

// this is wrong, it will overwrite the attachments
// mimeMessage.setContent(mails.getContent(),"text/html");

Upvotes: 5

Fatih Doğmuş
Fatih Doğmuş

Reputation: 531

Ok i solved the problem. The problem was i was setting the content of the mimeMessage directly so it overrode the addAttachment and other content wise configs.

Upvotes: 1

Related Questions