Gmail API 不会将我的附件识别为附件,而是将我的附件识别为多部分/混合,为什么?

Gmail API doesn't recognize my attchments as attachments but as multipart/mixed why?

提问人:Mr12 提问时间:10/24/2023 最后编辑:Mark RotteveelMr12 更新时间:10/24/2023 访问量:20

问:

我发送带有附件的邮件的方法有效,但是,API 不会将我的附件识别为附件,而是将我的附件识别为多部分/混合附件。 这很烦人,因为我需要附件的 ID 才能完成应用程序的其余部分。

{
    "folder": [
        "SENT"
    ],
    "sender": "-----------",
    "recipientTo": [
        "---------"
    ],
    "recipientCc": [
        "---------"
    ],
    "recipientBcc": [
        ""
    ],
    "subject": "test attachment",
    "body": "Contenu du mail avec <strong>balise</strong> <span style='color:red;'>HTML</span> Morbi molestie mattis lobortis.<br> Donec blandit euismod eleifend. Aenean eleifend ullamcorper aliquam. Suspendisse aliquam gravida sapien, ut elementum elit. Quisque porttitor efficitur nunc tincidunt dignissim. Sed sollicitudin iaculis enim. Donec at purus quis leo lacinia aliquam.",
    "hasAttachments": false,
    **"contentType": "multipart/mixed",**
    "receivedDateTime": "2023-10-24T07:57:00.000+00:00",
    "read": true
}

我的印象是我正在正确添加我的附件。

private MimeMessage createMimeMessageWithAttachments(final MailObjectRequestPayload mail) throws MessagingException, IOException {

    final List<MultipartFile> attachments = mail.getAttachment();

    // Create a new MimeMessage
    final Session session = Session.getDefaultInstance(new Properties());
    final MimeMessage mimeMessage = new MimeMessage(session);

    // Set the email subject, content, and recipients
    mimeMessage.setSubject(mail.getSubject());

    final Multipart multipart = new MimeMultipart();

    final MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(mail.getBody(),"text/html");
    multipart.addBodyPart(htmlPart);

    for (MultipartFile attachment : attachments) {

        final MimeBodyPart attachmentPart = new MimeBodyPart();
        ByteArrayDataSource source = new ByteArrayDataSource(attachment.getBytes(), attachment.getContentType());
        attachmentPart.setDataHandler(new DataHandler(source));
        attachmentPart.setFileName(attachment.getOriginalFilename());

        // add the file to the multipart
        multipart.addBodyPart(attachmentPart);
    }

    mimeMessage.setContent(multipart);
    return mimeMessage;
}
Java jakarta-mail gmail-api 多部分

评论


答:

0赞 Jorn 10/24/2023 #1

你必须把整个事情包装在一个“替代”部分中:

MimeMessage mimeMessage = ...;
MimeMultipart content = new MimeMultipart("alternative");

MimeBodyPart plain = new MimeBodyPart();
plain.setContent(..., "text/plain");
content.addBodyPart(plain);

MimeBodyPart html = new MimeBodyPart();
html.setContent(..., "text/html");
content.addBodyPart(html);

MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName(...);
attachment.setDataHandler(...);
content.addBodyPart(attachment);

mimeMessage.setContent(content);

评论

0赞 Mark Rotteveel 10/24/2023
不过,使用 multipart/mixed 应该可以。问题更有可能是 OP 没有设置处置setDisposition(Part.ATTACHMENT);