Sendgrid Inbound Parse webhook and Java MimeMessage Compatibility

Viewed 264

I am trying to parse raw mime message which sengrid post to a URL by inbound parse web hook settings. Previously i was listening for incoming mails from Mailserver through Imap and from java MimeMessage i was able to convert it to the String and vice versa. Please see below code how i used to convert from MimeMessage to String and vice versa in java.

private void convertMimeMessageToStringAndViceVersa(javax.mail.internet.MimeMessage message) {

        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        message.writeTo(bStream);
        String rawMimeMessageString = new String(bStream.toByteArray(), StandardCharsets.UTF_8.name());

        // Now from the above String to MimeMessage see below code
        
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        ByteArrayInputStream bais = new ByteArrayInputStream(rawMimeMessageString.getBytes());
        javax.mail.internet.MimeMessage convertedMimeMessage = new MimeMessage(session, bais);
        
}

So my question is, i cannot convert the string raw mail message which sendgrid is posting through inbound parse webhook to javax.mail.internet.MimeMessage type. Is there anyway.

1 Answers

Probably SendGrid Raw MimeMessage is broken, however you can try to use non-raw payload and convert this payload to whatever you want.

According to this article: https://varunsastrydevulapalli.medium.com/the-sendgrid-inbound-webhook-with-spring-dc7b5bae4e0c, we can receive the Inbound Message using this spring controller:

@Controller
@RequestMapping(value = "/messaging")
public class InboundMessageController {
@Bean(name = "multipartResolver")
 public CommonsMultipartResolver commonsMultipartResolver() {
 CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
 commonsMultipartResolver.setDefaultEncoding("UTF-8");
 commonsMultipartResolver.setMaxUploadSize(5000);
 return commonsMultipartResolver;
 }
 
 @RequestMapping(value = "/inbound", method = {RequestMethod.POST, RequestMethod.HEAD}, consumes = MediaType.MULTIPART_FORM_DATA)
 public @ResponseBody
 void processInboundSendGridEmails(HttpServletRequest request,
 HttpServletResponse response,
 @RequestParam(required = false) MultipartFile file,
 SendGridInbound sendGridInbound) {
  System.out.println(sendGridInbound);
  convertToMimeMessage(sendGridInbound);
 }
}

public class SendGridInbound {
    String headers;
    String dkim;
    String to;
    String html;
    String from;
    String text;
    String sender_ip;
    String spam_report;
    String envelope;
    String attachments;
    String subject;
    String spam_score;
    String attchmentInfo;
    String charsets;
    String spf;

    //getter setters toString
}

Hope it could help.

Related