java javamail问题:如何在不创建文件的情况下附加文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3556091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javamail problem: how to attach file without creating file
提问by moa
I'm using javamail API to create e-mail and attach a file to it.
我正在使用 javamail API 创建电子邮件并向其附加文件。
Is there a way to send e-mail with attach using javamail api without physically creating file on file system.
有没有办法使用 javamail api 发送带有附件的电子邮件,而无需在文件系统上物理创建文件。
I just want to pick some data from app and attach it as file in my e-mail
我只想从应用程序中选择一些数据并将其作为文件附加到我的电子邮件中
How should I attach:
我应该如何附加:
try {
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(msgText1);
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the message
**mbp2.attachFile(filename);**
// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
// set the Date: header
msg.setSentDate(new Date());
// send the message
Transport.send(msg);
TY very much all !
TY都非常!
回答by Nikolaus Gradwohl
If you are using JavaMail 1.4 or higher you can use java.mail.util.ByteArrayDataSourcelike this
如果您使用的是 JavaMail 1.4 或更高版本,您可以java.mail.util.ByteArrayDataSource像这样使用
MimeBodyPart mbp = new MimeBodyPart();
String data = "any ASCII data";
DataSource ds = new ByteArrayDataSource(data, "application/x-any");
mbp.setDataHandler(new DataHandler(ds));

