【问题标题】:How to enable attachment using Apache File upload如何使用 Apache 文件上传启用附件
【发布时间】:2010-04-24 10:29:49
【问题描述】:

我正在使用 Apache commons File upload API 将文件从 JSP 存储到 temp 目录中的 servlet,但我不知道接下来应该怎么做才能使用 javamail API 将电子邮件作为附件发送。

如何使用 Apache Fileupload API 检索那些写入临时目录的文件,以将它们作为附件发送到邮件服务器。将这些文件写入内存或磁盘对我有何帮助?

【问题讨论】:

    标签: java jsp servlets file-upload jakarta-mail


    【解决方案1】:

    这是一个例子:

    private static void notify(String subject, String text,
            File attachment, String from, String to) throws Exception {
        Context context = new InitialContext();
        Session sess = (Session)context.lookup("java:comp/env/mail/session");
        MimeMessage message = new MimeMessage(sess);
        message.setSubject(subject, "UTF-8");
        if (attachment == null) {
            message.setText(text, "UTF-8");
        } else {
            MimeMultipart mp = null;
            MimeBodyPart part1 = new MimeBodyPart();
            part1.setText(text, "UTF-8");
            MimeBodyPart part2 = new MimeBodyPart();
            part2.setDataHandler(new DataHandler(new FileDataSource(attachement)));
            part2.setFileName(file.getName());
            mp = new MimeMultipart();
            mp.addBodyPart(part1);
            mp.addBodyPart(part2);
            message.setContent(mp);
       }
    
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        Transport.send(message);
    }
    

    在此示例中,使用了 FileDataSource,这意味着必须首先将附件保存为文件。 我有时会改用自制的 MemoryDataSource。代码如下:

    package com.lagalerie.mail;
    
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import javax.activation.DataSource;
    
    public class MemoryDataSource implements DataSource {
        private String name;
        private String contentType;
        private byte content[] = {};
    
        public MemoryDataSource(String name, String contentType) {
            this.name = name;
            this.contentType = contentType;
        }
    
        public String getContentType() {
            return contentType;
        }
    
        public InputStream getInputStream() {
            return new ByteArrayInputStream(content);
        }
    
        public String getName() {
            return name;
        }
    
        public OutputStream getOutputStream() {
            return new ByteArrayOutputStream() {
                @Override
                public void close() {
                    content = toByteArray();
                }
            };
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      • 2010-11-11
      • 2010-09-18
      • 2017-11-05
      相关资源
      最近更新 更多