2

将多个添加MimeBodyPartMimeMultiPart. 本质上,如果MimeMultiPart是混合的,则所有MimeBodyPart对象都作为附件添加,除了最后一个,它添加到正文中。如果MimeMultiPart是可选的,那么只有最后一个MimeBodyPart被添加到正文中。

我只是想写一封简单的电子邮件,它应该有一个开头(文本),然后是一个表格(html),最后是一个结尾(文本)。

代码

这是我创建电子邮件的函数的代码。它生成MimeMessage然后在 Outlook 中将其作为草稿打开。

public void writeEmail() throws Exception {
        //Create message envelope.
        MimeMessage msg = new MimeMessage((Session) null);
        
        //Set destination and cc
        msg.addFrom(InternetAddress.parse("SELECT@ACCOUNT"));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("support@bar.com"));
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse("manager@baz.com"));
        
        //Create and set the subject
        String subject = "subject"; 
        
        msg.setSubject(subject);
        
        //Make the message as a draft
        msg.setHeader("X-Unsent", "1");

        
        //Create the body
        MimeMultipart mmp = new MimeMultipart("alternative");
        
        //Tests
        String opening = "Opening";
        String html = "<h1>" + table + "</h1>";
        String closing = "Closing";
        
        MimeBodyPart openingPart = new MimeBodyPart();
        openingPart.setDisposition(MimeBodyPart.INLINE);
        openingPart.setText(opening, "utf-8");
        
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setDisposition(MimeBodyPart.INLINE);
        htmlPart.setContent(html, "text/html; charset=utf-8");
        
        MimeBodyPart closingPart = new MimeBodyPart();
        closingPart.setDisposition(MimeBodyPart.INLINE);
        closingPart.setText(closing, "utf-8");
        
        mmp.addBodyPart(openingPart);
        mmp.addBodyPart(htmlPart);
        mmp.addBodyPart(closingPart);
        
        msg.setContent(mmp);
        msg.saveChanges();

        //Save as a temporary file
        File resultEmail = File.createTempFile("email", ".eml");
        
        try (FileOutputStream fs = new FileOutputStream(resultEmail)) {
            msg.writeTo(fs);
            fs.flush();
            fs.getFD().sync();
        }

        System.out.println(resultEmail.getCanonicalPath());

        ProcessBuilder pb = new ProcessBuilder();
        pb.command("cmd.exe", "/C", "start", "outlook.exe", "/eml", resultEmail.getCanonicalPath());
        Process p = pb.start();
        
        try {
            p.waitFor();
        } finally {
            p.getErrorStream().close();
            p.getInputStream().close();
            p.getErrorStream().close();
            p.destroy();
        }
}

问题

如何MimeBodyPart在电子邮件正文中呈现所有文本,而不是将它们错误地添加为附件?

4

0 回答 0