首页 > 解决方案 > Sendgrid Inbound Parse webhook 和 Java MimeMessage 兼容性

问题描述

我正在尝试通过入站解析 Web 挂钩设置解析 sengrid 发布到 URL 的原始 mime 消息。以前我通过 Imap 和 java MimeMessage 监听来自 Mailserver 的传入邮件,我能够将其转换为字符串,反之亦然。请参阅下面的代码,我过去是如何在 java 中从 MimeMessage 转换为 String 的,反之亦然。

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);
        
}

所以我的问题是,我无法将 sendgrid 通过入站解析 webhook 发布的字符串原始邮件消息转换为 javax.mail.internet.MimeMessage 类型。反正有没有。

标签: sendgridsendgrid-api-v3sendgrid-api-v2

解决方案


SendGrid Raw MimeMessage 可能已损坏,但是您可以尝试使用非原始有效负载并将此有效负载转换为您想要的任何内容。

根据这篇文章:https ://varunsastrydevulapalli.medium.com/the-sendgrid-inbound-webhook-with-spring-dc7b5bae4e0c ,我们可以使用这个spring控制器接收入站消息:

@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
}

希望它可以帮助。


推荐阅读