Search code examples
javajsonsmtpjakarta-maileml

MimeMessage emlMessage = new MimeMessage(session, emlInputStream); throwing InvocationTargetException


I have written a code to parse .eml file to a JSON file. I'm using the below dependency

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>jakarta.mail</artifactId>
    <version>2.0.1</version>
</dependency>

Here is my code

/**
     * Convert .eml file to .json file
     *
     * @param inputFile     .eml file
     * @param outputFile    .json file
     * @return  output file
     * @throws Exception Exception
*/
public File executeTransform(File inputFile, File outputFile) throws Exception {
        try {
            Properties properties = new Properties();
            Session session = Session.getDefaultInstance(properties);

            // Read the .eml file
            InputStream emlInputStream = new FileInputStream(inputFile);
            MimeMessage emlMessage = new MimeMessage(session, emlInputStream);

            // Convert the email message to JSON. convertEmlToJson() This function reads eml, extracts required data from it, puts that data in ObjectNode, and returns that ObjectNode.
            ObjectNode jsonNode = convertEmlToJson(emlMessage);

            // Write JSON to a file
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
            objectMapper.writeValue(outputFile, jsonNode);
        } catch (Exception e) {
            System.err.println("Test log : error occurred " + e.getMessage());
            throw e;
        }
        return outputFile;
    }

While running this code I'm getting below error

java.lang.reflect.InvocationTargetException and cause java.lang.NoSuchMethodError: 'void com.sun.mail.util.LineInputStream.<init>(java.io.InputStream, boolean)'

And getting above error for this line

MimeMessage emlMessage = new MimeMessage(session, emlInputStream);

Does anyone know what I need to do to resolve this issue?


Solution

  • I resolved this issue by adding the below dependency instead jakarta.mail

    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.6.2</version>
    </dependency>
    

    I'm using JAVA11. And before Java 17 jakarta.mail was javax.mail.

    If you want to use jakarta.mail, you have to upgrade to Java17, which has jakarta.mail API built-in, or

    javax.mail will work with Java11 or less.