1

I have a scenario where i get a big error log string, which is not good idea to send it as mail text. So , we need to generate text file and send it as mail attachment.

If there is any way to create a file in memory and send it as attachment that would be good instead of creating physical file?

Following is my code:

void sendEmail(String errorlog) {
    try {
        MimeMessagePreparator messagePreparator = mimeMessage -> {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
            messageHelper.setFrom("sachin@gmail.com"); 
            messageHelper.setTo(InternetAddress.parse("akash@gmail.com"));
            messageHelper.setSubject("error log");
            messageHelper.setText(" Please find log attachment:");

            File <somehow crate text file from parameterized string>

            messageHelper.addAttachment("log.ext",file);

        };
        javaMailSender.send(messagePreparator);

    } catch (Exception e) {
    }
}
Maurice Perry
  • 8,497
  • 2
  • 10
  • 23
Anonymous
  • 1,616
  • 4
  • 21
  • 44

3 Answers3

1

There is an another addAtachment method in the MimeMessageHelper which can help you to add attachment without creating file.

addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)

You can easily create inputStream with given string

InputStream inputStream = new ByteArrayInputStream(string.getBytes(Charset.forName("UTF-8")));

After that create inputStreamResourceSource which implements inputStreamSource

addAttachment("log.ext",new InputStreamResource(inputStream));
Doğukan HAN
  • 113
  • 2
  • 6
0

Just use FileUtils.writeStringToFile() from Apache Commons IO.

How do I save a String to a text file using Java?

n2ad
  • 183
  • 1
  • 7
0

So I have had the same issue and none of these answers worked for me - when trying to use MimeMessageHelper like in this answer I was getting an "Passed-in resource contains an open stream" error. In the end, I was able to solve this problem by preparing body of my e-mail step by step, like this:

Multipart multipart = new MimeMultipart();
BodyPart attachmentBodyPart = new MimeBodyPart(new ByteArrayInputStream(string.getBytes()));                          
attachmentBodyPart.setFileName("filename.ext");
attachmentBodyPart.setDisposition(Part.ATTACHMENT);
multipart.addBodyPart(attachmentBodyPart);

mimeMessage.setContent(multipart);

Note that when mixing up this approach with using MimeMessageHelper, mimeMessage.setContent() will overwrite any content added by MimeMessageHelper (so for example text you want to send in body of your e-mail), which I solved by adding to multipart additional BodyPart that contained the text I wanted to send inside my e-mail.

jojo
  • 72
  • 1
  • 9