javaemailsendgridmime-message

Java - Convert the Raw Email Content Text RFC 822 to MimeMessage


Looking for an option to convert the raw email message RFC 822 to java MimeMessage object. MimeMessage has an option to convert the object to raw email context using MimeMessage#writeTo, self looking best approach of vice versa.

Background:

Sendgrid - Inbound parse invoke API and sent the raw email content part of json payload, from which we have to collect the email content and attachment files.


Solution

  •     String rawEmailString = "";
        InputStream targetStream = new ByteArrayInputStream(rawEmailString.getBytes());
        Session session = null;
        MimeMessage mimeMessageObj;
        try {
    
            // raw message to mime conversion - start
    
            mimeMessageObj = new MimeMessage(session, targetStream); 
    
            // raw message to mime conversion - end
    
            // bonus line of code to play with the message
            MimeMessageParser mimeParser = new MimeMessageParser(mimeMessageObj);
            mimeParser.parse();
            List<javax.mail.Address> to = mimeParser.getTo();
            String from = mimeParser.getFrom();
            String subject = mimeParser.getSubject();
            String bodyPlain = mimeParser.getPlainContent();
            String bodyHtml = mimeParser.getHtmlContent();
            System.out.println("From id >>>>>>>>>> " + from);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    

    for org.apache.commons.mail.util.MimeMessageParser; you can use

       <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.3</version>
        </dependency>