Java 发送附件时不显示正文消息
发送附件时,我在电子邮件中看不到正文消息(message.setText(this.getEmailBody());)。 如果没有附件,电子邮件将显示正文消息。电子邮件被发送到gmail帐户。你知道为什么会这样吗Java 发送附件时不显示正文消息,java,jakarta-mail,Java,Jakarta Mail,发送附件时,我在电子邮件中看不到正文消息(message.setText(this.getEmailBody());)。 如果没有附件,电子邮件将显示正文消息。电子邮件被发送到gmail帐户。你知道为什么会这样吗 MimeMessage message = new MimeMessage(session_m); message.setFrom(new InternetAddress(this.getEmailSender())); mess
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");
您需要使用以下各项:
// 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
要执行此操作,您需要分成两部分:
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);
整个方法。它对我有用。检查我是否遗漏了片段中的某些内容。这是全部,你说得对。这对我也有用。我认为问题出在这两行:MimeBodyPart messageBodyPart=newmimebodypart();messageBodyPart.attachFile(this.attachmentsDir.concat(file.trim());所以我必须按你的方式做。谢谢你的帮助;)非常感谢,这是唯一对我有效的解决方案+1.