将上传的文件附加为电子邮件 [英] Attach the uploaded file as an email
问题描述
我正在使用apache commons fileupload上传文件。我想把这个文件附加到一个电子邮件。我不想写入临时文件,但我想保留在内存中的数据,并将其作为附件发送。我需要从这里来的方向。提前感谢
DiskFileItemFactory factory = new DiskFileItemFactory();
PortletFileUpload upload = new PortletFileUpload(factory);
List items = upload.parseRequest(request);
Iterator iter = items.iterator(); (iter.hasNext()){
FileItem item =(FileItem)iter.next();
while
if(item.isFormField()){
String name = item.getFieldName();
String value = item.getString();
response.setRenderParameter(name,value);
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
// String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
InputStream uploadedStream = item.getInputStream();
$ b code
$ b 更新
我有以下方法签名发送一个电子邮件与附件,它的工作正常。
pre $ sendWithFileAttachment(String [ ]
字符串主题
文件信息
字符串从
字符串文件名$ {
BodyPart messageBodyPart = new MimeBodyPart();
//填写消息
messageBodyPart.setText(Pardon Ideas);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//第二部分是附件
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(message);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
//将部分放入消息
msg.setContent(multipart);
Transport.send(msg);
}
更新2 :
在执行代码后,我得到了下面的错误。你可以帮我一下吗?
HIT ME! 15782
2012年7月31日上午11:17:56 test.test.EmailUtility1 $ InputStreamMimeBodyPart getContentStream
SEVERE:null
可能发生:java.io.IOException:流关闭
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:156)
在java.io.BufferedInputStream.reset(BufferedInputStream.java:425)
at test.test.EmailUtility1 $ InputStreamMimeBodyPart.getContentStream(EmailUtility1。在javax.mail.internet.MimePartDataSource.getInputStream中
(MimePartDataSource.java:94)$ b $在javax.activation.DataHandler.writeTo(DataHandler.java:302)
在javax .mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:845)
at javax.mail.internet.MimeMultipart.writeTo (MimeMultipart.java:361)
at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:85)
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:881 )
at javax.activation.DataHandler.writeTo(DataHandler.java:314)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
at javax.mail。 internet.MimeMessage.writeTo(MimeMessage.java:1683)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:585)
at javax.mail.Transport.send0(Transport。 java:169)
at javax.mail.Transport.send(Transport.java:98)
at test.test.EmailUtility1.sendWithFileAttachment(EmailUtility1.java:155)
at test.test .TestEmail.main(TestEmail.java:32)
线程main中的异常javax.mail.MessagingException:发送消息时发生IOException;
嵌套异常是:
java.io.IOException:流在com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:625)$ java
处关闭了
。 mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at test.test.EmailUtility1.sendWithFileAttachment(EmailUtility1.java:155)
at test.test.TestEmail.main(TestEmail.java:32)
导致:java.io.IOException:流关闭
在java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java :156)
在java.io.BufferedInputStream.read(BufferedInputStream.java:319)
在java.io.FilterInputStream.read(FilterInputStream.java:101)
$ c $你需要重写MimeBodyPart(你最有可能使用的,我假设),以便能够使用MimeBodyPart通过Stream获得他们的内容。
$ b $ pre $ public $ sendWithFileAttachment(String收件人
字符串主题,
InputStream消息,
字符串,
字符串文件名)抛出MessagingException {
MimeMessage msg = new MimeMessage(getSession());
//设置地址和地址
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress addressTo =新的InternetAddress(收件人);
msg.setRecipient(Message.RecipientType.TO,addressTo);
BodyPart messageBodyPart = new MimeBodyPart();
//填写消息
messageBodyPart.setText(Pardon Ideas);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//第二部分是附件
messageBodyPart = new InputStreamMimeBodyPart(message);
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
//将部分放入消息
msg.setContent(multipart);
Transport.send(msg);
// important:你需要手动关闭消息流
try {
message.close();
} catch(IOException ex){
// meh。所以呢。
$ b private class InputStreamMimeBodyPart extends MimeBodyPart {
private InputStream inputStream;
public InputStreamMimeBodyPart(InputStream source){
this.inputStream = source;
if(!inputStream.markSupported()){
throw new IllegalArgumentException(只有支持标记的流才好);
}
inputStream.mark(Integer.MAX_VALUE); //记住整个流。
$ b @Override
protected InputStream getContentStream()抛出MessagingException {
抛出新的IllegalStateException(getContentStream没有被实现。
$ b @Override
public void writeTo(OutputStream os)throws IOException,MessagingException {
System.out.println(write to somewhere。);
byte [] buf = new byte [32];
int长度;
inputStream.reset(); ((length = inputStream.read(buf))> -1){
os.write(buf,0,length);
$ b私有会话getSession(){
//在这里你做认证等
属性properties = new Properties ();
返回Session.getInstance(properties);
}
I am using the apache commons fileupload for uploading the file. I want to attach this file to an email. I don't want to write to temp file but I want to keep the data in memory and send it as an attachment. I need direction from here. Thanks in advance
DiskFileItemFactory factory = new DiskFileItemFactory();
PortletFileUpload upload = new PortletFileUpload(factory);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while(iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
response.setRenderParameter(name, value);
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
//String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
InputStream uploadedStream = item.getInputStream();
}
}
UPDATE I have the following method signature for sending an email with attachement and its working fine.
sendWithFileAttachment (String[] recipients,
String subject,
File message,
String from,
String filename) {
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("Pardon Ideas");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(message);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(multipart);
Transport.send(msg);
}
UPDATE 2: I am getting the below error after implementing your code. Can you please help me with this
HIT ME! 15782
Jul 31, 2012 11:17:56 AM test.test.EmailUtility1$InputStreamMimeBodyPart getContentStream
SEVERE: null
Throwable occurred: java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:156)
at java.io.BufferedInputStream.reset(BufferedInputStream.java:425)
at test.test.EmailUtility1$InputStreamMimeBodyPart.getContentStream(EmailUtility1.java:174)
at javax.mail.internet.MimePartDataSource.getInputStream(MimePartDataSource.java:94)
at javax.activation.DataHandler.writeTo(DataHandler.java:302)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:845)
at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:361)
at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:85)
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:881)
at javax.activation.DataHandler.writeTo(DataHandler.java:314)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1683)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:585)
at javax.mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at test.test.EmailUtility1.sendWithFileAttachment(EmailUtility1.java:155)
at test.test.TestEmail.main(TestEmail.java:32)
Exception in thread "main" javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.IOException: Stream closed
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:625)
at javax.mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at test.test.EmailUtility1.sendWithFileAttachment(EmailUtility1.java:155)
at test.test.TestEmail.main(TestEmail.java:32)
Caused by: java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:156)
at java.io.BufferedInputStream.read(BufferedInputStream.java:319)
at java.io.FilterInputStream.read(FilterInputStream.java:101)
You need to override MimeBodyPart (which you are most likely using, I assume) to be able to get their content through a Stream.
public void sendWithFileAttachment(String recipient,
String subject,
InputStream message,
String from,
String filename) throws MessagingException {
MimeMessage msg = new MimeMessage(getSession());
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress addressTo = new InternetAddress(recipient);
msg.setRecipient(Message.RecipientType.TO, addressTo);
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("Pardon Ideas");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new InputStreamMimeBodyPart(message);
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(multipart);
Transport.send(msg);
// important: you need to close the message stream manually
try {
message.close();
} catch (IOException ex) {
// meh. So what.
}
}
private class InputStreamMimeBodyPart extends MimeBodyPart {
private InputStream inputStream;
public InputStreamMimeBodyPart(InputStream source) {
this.inputStream = source;
if(!inputStream.markSupported()) {
throw new IllegalArgumentException("only streams with mark supported are ok");
}
inputStream.mark(Integer.MAX_VALUE); // remeber the whole stream.
}
@Override
protected InputStream getContentStream() throws MessagingException {
throw new IllegalStateException("getContentStream is not implemented on purpose.");
}
@Override
public void writeTo(OutputStream os) throws IOException, MessagingException {
System.out.println("writing to somewhere.");
byte[] buf = new byte[32];
int length;
inputStream.reset();
while((length = inputStream.read(buf)) > -1 ) {
os.write(buf, 0, length);
}
}
}
private Session getSession() {
// here you do authentication etc.
Properties properties = new Properties();
return Session.getInstance(properties);
}
这篇关于将上传的文件附加为电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!