2

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
  • 9,261
  • 2
  • 12
  • 24
Anonymous
  • 1,726
  • 4
  • 22
  • 47

4 Answers4

2

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
  • 123
  • 2
  • 6
0

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

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

n2ad
  • 323
  • 2
  • 8
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.

0

I host a Spring Boot application in Docker on my VPS. This code will work on a local system whilst developing in an IDE as well as if the .JAR-file is wrapped in a Docker image:

Example case:

I like to get a PDF. The PDf document is located at static/docs/not-a-porn.PDF.

1.) Wire the class ResourceLoader and JavaMailSender.

private final JavaMailSender emailSender;
private final ResourceLoader resourceLoader;

public MyService(@Autowired JavaMailSender emailSender, @Autowired ResourceLoader resourceLoader) {
    this.emailSender = emailSender;    
    this.resourceLoader = resourceLoader;
}

2.) Create a resource by pathOfAttachment (String).

String pathOfAttachment = "classpath:static/docs/not-a-porn.PDF"
Resource resource = this.resourceLoader.getResource(pathOfAttachment);

Resource is an interface that extends InputStreamSource as you can see in the documentation:

public interface Resource extends InputStreamSource

Source: org.springframework.core.io Link to documentation (click here)

3.) Define e-mail's metadata.

MimeMessageHelper helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.name());

helper.setFrom(Text.EMAIL_COMPANY);
helper.setTo("myMail@gmail.com");
helper.setSubject("MySubject");
helper.setText("Hello from Spring Boot application", true);

3.) Attach file to e-mail attachments.

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

4.) Send e-mail.

this.emailSender.send(message);
Kevin O.
  • 355
  • 3
  • 11