我的情况是这样的:
我有一个 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
有谁知道是什么导致了这个错误,我该如何解决?