我正在尝试从 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
它,它包含图像。