Java发送附件的电子邮件,DataContentHandler上的错误

时间:2013-07-02 09:18:24

标签: java javamail

我的情况是:

我有一个Web应用程序,用户编写消息,附加文件并发送电子邮件。

我使用JavaMail发送这样的邮件但我在将文件附加到邮件时遇到问题(我的文件在Session上):

        if (request.getSession().getAttribute("EMAIL_ATTACHMENT") != null) {
            UploadFile file = (UploadFile) request.getSession().getAttribute("EMAIL_ATTACHMENT");
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(text, "text/html;charset=UTF-8");
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            MyMailAttachmentDataSource fds = new MyMailAttachmentDataSource(file);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
            msg.setContent(mp, "text/plain");

        }

MyMailAttachmentDataSource的代码是:

public class MyMailAttachmentDataSource implements DataSource{
    private UploadFile file; 
    public MyMailAttachmentDataSource(UploadFile file){
        this.file=file;
    }
    @Override
    public InputStream getInputStream() throws IOException {
        return file.getInpuStream();
    }
    @Override
    public OutputStream getOutputStream() throws IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    @Override
    public String getContentType() {
        return file.getContentType();
    }
    @Override
    public String getName() {
        return file.getFileName();
    }
}

当我尝试发送电子邮件时,我收到此异常

java.io.IOException: "text/plain" DataContentHandler requires String object, was given object of type class javax.mail.internet.MimeMultipart
at com.sun.mail.handlers.text_plain.writeTo(text_plain.java:97)
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:884)
at javax.activation.DataHandler.writeTo(DataHandler.java:317)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1089)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1527)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:321)
at admin.email.JavaMail.SendEmail(JavaMail.java:403)
at admin.email.MailSend.SendMail(MailSend.java:86)

我尝试将msg.contentType更改为“text / html”但仍然获得上述异常

"text/html" DataContentHandler requires String object, was given object of type class javax.mail.internet.MimeMultipart

有谁知道导致此错误的原因以及如何解决?

1 个答案:

答案 0 :(得分:4)

附件电子邮件的格式不能为text/plaintext/html,而应为multipart/mixed

似乎将代码行msg.setContent(mp, "text/plain");更改为已足够 只是msg.setContent(mp);