gpt4 book ai didi

java - 使用 MimeMultipart(附件文件 + 文本)和 JBoss 6.3 发送 MimeMessage

转载 作者:行者123 更新时间:2023-11-30 06:04:24 25 4
gpt4 key购买 nike

我正在尝试在我的 java 程序中发送一封带有附件的电子邮件。

但是我遇到了一个问题,当我通过 JBoss 服务器执行代码时,我收到一封空邮件(没有任何 HTML 标签)。当我通过 JUnit 测试执行代码时。

我收到带有附件和正文的邮件。

使用相同的输入数据,相同的邮件服务器,我面临两种不同的行为。

当我不使用 mail.setContent 函数时,我在 2 环境(JBoss 和 JUnit 测试)中收到一封带有正文的邮件。

看来我的问题与 setContent 函数、MimeMultipart 类型和 JBoss 执行有关。

我使用:

  • Java jdk1.7.0_79

  • Maven 3.3.9

  • JBoss EAP 6.3

  • javax.mail 版本:1.6.0

这是我发送带有附件的邮件的代码:

    public void sendWithAttachment(ByteArrayOutputStream  attachmentByte, String filename) {


Properties properties = new Properties();
properties.setProperty("mail.smtp.host", "myhost");
properties.setProperty("mail.smtp.port", "myport");


try {
final Address[] reply = {new InternetAddress("foo@test.fr")};

final Session session = Session.getDefaultInstance(properties, null);

final MimeMessage mail = new MimeMessage(session);

String recipient = "foo-recipient@test.fr";
String body = "test";
mail.setFrom(new InternetAddress("foo@test.fr","foo@test.fr"));
mail.setSubject("subject");
mail.setReplyTo(reply);
MimeMultipart multipart = generateAttachment(attachmentByte,filename,body);
mail.setContent(multipart);

final Transport transport = session.getTransport("smtp");
transport.connect();

mail.setRecipient(Message.RecipientType.TO, new InternetAddress(destinataire,destinataire));
transport.sendMessage(mail, mail.getAllRecipients());
transport.close();
} catch (final MessagingException | UnsupportedEncodingException me) {
me.printStackTrace();
}
}

private MimeMultipart generateAttachment(ByteArrayOutputStream attachmentByte, String filename, String body) throws MessagingException {
MimeMultipart res = new MimeMultipart();
byte[] poiBytes = attachmentByte.toByteArray();

DataSource dataSource = new ByteArrayDataSource(poiBytes, "application/octet-stream");
BodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
attachmentBodyPart.setFileName(filename);

BodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText(body);
textBodyPart.setContent(body, "text/html; charset=utf-8");

res.addBodyPart(textBodyPart);
res.addBodyPart(attachmentBodyPart);
return res;
}

您有什么想法或线索可以解决我的问题吗?

谢谢

最佳答案

我知道这是一件小事,但我注意到您的端口和主机属性设置为相同。

Properties properties = new Properties();
properties.setProperty("mail.smtp.host", "myhost");
properties.setProperty("mail.smtp.host", "myport");

他们应该是

Properties properties = new Properties();
properties.setProperty("mail.smtp.host", "myhost");
properties.setProperty("mail.smtp.port", "myport");

我找到了这个页面,https://www.journaldev.com/2532/javamail-example-send-mail-in-java-smtp最近运行 poc 时很有帮助。

关于java - 使用 MimeMultipart(附件文件 + 文本)和 JBoss 6.3 发送 MimeMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51655237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com