Search code examples
javaspringfile-iojakarta-mail

Sending Selenium report to e-mail


Im trying to send a Selenium report to my e-mail address.

In my pom I have added spring-context-support and javax.mail-api.

The problem is that I dont know how to read a HTML page into a InputStreamSource, so I can send it to my e-mail address. Can someone please show me? Here is my method for sending e-mail:

private void sendMail() {

    MimeMessage message = mailSender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        if (emailTo.contains(",")) {
            helper.setTo(emailTo.split(","));
        } else {
            helper.setTo(emailTo);
        }
        helper.setFrom("[email protected]");
        helper.setSubject("Selenium: Something went wrong");
        helper.setText("Please see the attached report");

        // I need help with this:
        InputStreamSource iss = getInputSteam("Testresult.html");




        helper.addAttachment("Testresult.html", iss,
                "text/html; charset=UTF-8");
        mailSender.send(message);
    } catch (javax.mail.MessagingException me) {
        throw new RuntimeException("Messaging exception caught: " + me.getMessage());
    }
}

Solution

  • This should work if the HTML file can be accessed locally (make sure the file path to your file is correct):

    InputStreamSource iss = FileSystemResource("path/to/your/file");
    

    or this, if you can use a URL (in this case via HTTP):

    InputStreamSource iss = FileSystemResource(new URL("http://my.file.url"));
    

    Be aware that MimeMessageHelper has a method like this:

    addAttachment(String attachmentFilename, File file)
    

    which would be yet easier if you don't have to care about contentType.