发送带附件的电子邮件

时间:2015-06-12 14:42:57

标签: java javamail

我已经实现了简单的电子邮件服务,我希望通过文件附件进行扩展。这是到目前为止的代码:

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);
            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!";
    }

作为附件我想使用这个对象:

private Part file;

我尝试使用this代码以这种方式实现它:

private Part file;
........

MimeBodyPart messageBodyPart = new MimeBodyPart();

            Multipart multipart = new MimeMultipart();

            messageBodyPart = new MimeBodyPart();
//            String file = "path of file to be attached";
//            String fileName = "attachmentName";
            DataSource source = new FileDataSource((File) file);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(file.getName());
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

我收到此错误:

serverError: class javax.faces.el.EvaluationException org.apache.catalina.core.ApplicationPart cannot be cast to java.io.File

你能帮我解决问题吗?

1 个答案:

答案 0 :(得分:0)

替换:

// String file = "..."; DataSource source = new FileDataSource((File) file);

使用:

String pathToFile = "..."; DataSource source = new FileDataSource(new File(pathTofile));