我正在尝试使用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
,它包含图像。
答案 0 :(得分:1)
好的,我明白了。我不应该传递输入流,而是传递字节数组并设置更精确的MIME类型。我修改了我的代码,如下所示:
DataSource source = new ByteArrayDataSource(
IOUtils.toByteArray(is), "image/jpeg");
答案 1 :(得分:0)
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
来源:http://www.tutorialspoint.com/java/java_sending_email.htm