gpt4 book ai didi

java - 电子邮件缺少图片附件

转载 作者:行者123 更新时间:2023-12-01 15:08:44 24 4
gpt4 key购买 nike

我正在尝试从 Java 发送一封带有图像附件的电子邮件。我正在使用以下代码:

String to = "jverstry@gmail.com";
String from = "ffff@ooop.com";

// Which server is sending the email?
String host = "localhost";

// Setting sending mail server
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);

// Providing email and password access to mail server
properties.setProperty("mail.user", "xxx");
properties.setProperty("mail.password", "yyy");

// Retrieving the mail session
Session session = Session.getDefaultInstance(properties);

// Create a default MimeMessage
MimeMessage message = new MimeMessage(session);

message.setFrom(new InternetAddress(from));
message.addRecipient(
Message.RecipientType.TO, new InternetAddress(to));

message.setSubject("This an email test !!!");

// Create a multipart message
Multipart mp = new MimeMultipart();

// Body text
BodyPart messageBP = new MimeBodyPart();
messageBP.setText("Some message body !!!");
mp.addBodyPart(messageBP);

// Attachment
BodyPart messageBP2 = new MimeBodyPart();

String image = "/MyImage.jpg";
InputStream stream = EmailWithAttachment.class
.getResourceAsStream(image);
DataSource source = new ByteArrayDataSource(stream, "image/*");

messageBP2.setDataHandler(new DataHandler(source));
messageBP2.setHeader("Content-ID", "My Image");
mp.addBodyPart(messageBP2);

message.setContent(mp);

// Sending the message
Transport.send(message);

电子邮件已到达我的邮箱,但当我打开它时,附件不可用。什么可能导致此问题?我已检查 .jar,它包含图像。

最佳答案

好的,我明白了。我不应该传递输入流,而是传递一个字节数组并设置更精确的 MIME 类型。我修改了我的代码如下并且它有效:

DataSource source = new ByteArrayDataSource(
IOUtils.toByteArray(is), "image/jpeg");

关于java - 电子邮件缺少图片附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12603617/

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