6

当我发送附件时,我在电子邮件中看不到正文消息 (message.setText(this.getEmailBody());)。如果没有附件,电子邮件将与正文一起显示。电子邮件被发送到 gmail 帐户。任何线索为什么会发生这种情况?

        MimeMessage message = new MimeMessage(session_m);    
        message.setFrom(new InternetAddress(this.getEmailSender()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.getEmailRecipient()));
        message.setSubject(this.getEmailSubject());
        message.setText(this.getEmailBody()); //This won't be displayed if set attachments

        Multipart multipart = new MimeMultipart();

        for(String file: getAttachmentNameList()){
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.attachFile(this.attachmentsDir.concat(file.trim()));
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);
        }


        Transport.send(message);
        System.out.println("Email has been sent");
4

2 回答 2

9

您需要使用以下内容:

         // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Fill the message
        messageBodyPart.setText(body);
        messageBodyPart.setContent(body, "text/html");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
         //Add the bodypart for the attachment(s)
        // Send the complete message parts
        message.setContent(multipart); //message is of type - MimeMessage
于 2013-01-27T12:47:55.780 回答
2

你需要分成两部分来做到这一点:

        Multipart multipart = new MimeMultipart();

        // content part
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(content);
        messageBodyPart.setContent(content, "text/html");
        multipart.addBodyPart(messageBodyPart);

        BodyPart attachmentPart = new MimeBodyPart();
        DataSource source = new FileDataSource(file);
        attachmentPart.setDataHandler(new DataHandler(source));
        attachmentPart.setFileName(file.getName());
        multipart.addBodyPart(attachmentPart);
于 2016-07-25T04:55:27.650 回答