javax.mail.internet.ParseException:在Content-Type字符串中,期望'/',但得到了:

3
我想使用JSF实现带附件的邮件功能。我尝试了以下代码:
private Part file;

    private String sendFromGMail(String from, String pass, String[] to, String subject, String body)
    {
        String status;

        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);

        try
        {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for (int i = 0; i < to.length; i++)
            {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for (int i = 0; i < toAddress.length; i++)
            {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setText(body);

            MimeBodyPart messageBodyPart = new MimeBodyPart();
            Multipart multipart = new MimeMultipart();

            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(file, file.getName()));
            messageBodyPart.setFileName(file.getName());
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }
        catch (AddressException ae)
        {
            ae.printStackTrace();
            return status = "Cannot send Message!";
        }
        catch (MessagingException me)
        {
            me.printStackTrace();
            return status = "Cannot send Message!";
        }

        return status = "Message is send!";
    }

    //.......................

    public Part getFile() {
        return file;
    }

    public void setFile(Part file) {
        this.file = file;
    }

    public void upload() {

        if (file != null) {


            try (InputStream inputStream = file.getInputStream(); FileOutputStream outputStream = new FileOutputStream("D:" + File.separator + "files" + File.separator + file.getSubmittedFileName())) {

                int bytesRead = 0;
                final byte[] chunck = new byte[1024];
                while ((bytesRead = inputStream.read(chunck)) != -1) {
                    outputStream.write(chunck, 0, bytesRead);
                }

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload successfully ended!"));
            } catch (IOException e) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload failed!"));
            }
        }
    }

但是在Tomcat日志文件中,我收到了以下错误消息:
javax.mail.internet.ParseException: In Content-Type string <form:fileToUpload>, expected '/', got :
    at javax.mail.internet.ContentType.<init>(ContentType.java:103)
    at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1448)
    at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2190)
    at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2151)
    at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1846)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1196)
    at com.web.common.Contacts.sendFromGMail(Contacts.java:135)
    at com.web.common.Contacts.sendEmail(Contacts.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

有没有解决这个问题的方法?

在我的情况下,我想使用h:inputFile上传文件并将其作为电子邮件附件发送。但是我遇到了错误。


你有比较过从这里获取的代码吗?http://kahimyang.info/kauswagan/code-blogs/536/a-java-class-for-sending-multipart-email-messages-through-your-gmail-account - Mauricio Gracia Gutierrez
好的,但是这段代码使用了String []attachments。在我的情况下,我有二进制文件。 - Peter Penzov
@MauricioGracia 这个异常非常特殊,文档无法帮助。 - Peter Penzov
2
无法使用JSF发送电子邮件。此外,异常堆栈跟踪与JSF无关。最好删除JSF的干扰。 - Tiny
没错,这不是JSF的问题。在你尝试与JSF集成之前,先在“main”方法中让你的代码正常工作。 - DavidS
显示剩余6条评论
1个回答

8

我之前不是已经在别处回答过这个问题了吗?

使用Part.getInputStream()和ByteArrayDataSource

ByteArrayDataSource ds = new ByteArrayDataSource(file.getInputStream(), file.getContentType());
messageBodyPart.setDataHandler(new DataHandler(ds));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接