簡體   English   中英

Java發送附件的電子郵件,DataContentHandler上的錯誤

[英]Java Sending Email with attachment, error on DataContentHandler

我的情況是這樣的:

我有一個Web應用程序,用戶編寫消息,附加文件並發送電子郵件。

我使用JavaMail發送這樣的郵件,但我有問題將文件附加到郵件(我的文件在會話上):

        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

有誰知道導致此錯誤的原因以及如何解決?

帶附件的電子郵件不能是text/plaintext/html ,它應該是multipart/mixed

看來,改變代碼行msg.setContent(mp, "text/plain");就足夠了msg.setContent(mp, "text/plain"); 只是msg.setContent(mp);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM