该文件永远不会在JavaMail中发送

时间:2013-02-09 09:02:01

标签: java smtp javamail

我正在尝试使用JavaMail API发送附件,并且它无法正常工作。你能否告诉我我犯的错误,文件ABC.pdf在项目的同一个文件中。我确实在第一个sysout中的“s”中获得了正确的路径。该程序永远不会到达第二个sysout。我用电子邮件ID中的“试用”替换了Id。 请帮忙

Message message = new MimeMessage(session);
        message.setSubject("Trial Messages");
        message.setFrom(new InternetAddress("trial@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("trial@yahoo.co.in"));

        MimeBodyPart body = new MimeBodyPart();
        body.setText(content);;
        Multipart part = new MimeMultipart();

        part.addBodyPart(body);

        File f = new File("ABC.pdf");
        String s = f.getAbsolutePath();

        System.out.printf(s);

        DataSource source = new FileDataSource(s);
        body.setDataHandler(new DataHandler(source));
        body.setFileName("ABC Bill");
        part.addBodyPart(body);

        System.out.printf(s);
        Transport.send(message);

        System.out.printf(s);

1 个答案:

答案 0 :(得分:1)

尝试替换

body.setFileName("ABC Bill");

body.setFileName(source.getName());

您可以尝试将source.getName()传递给sysout以查看是否所有内容都正确(正确的文件名) 还添加

//将Multipart添加到消息

message.setContent(part);

删除part.addBodyPart(body);因为您添加了两次

Message message = new MimeMessage(session);
        message.setSubject("Trial Messages");
        message.setFrom(new InternetAddress("trial@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("trial@yahoo.co.in"));

        MimeBodyPart body = new MimeBodyPart();
        body.setText(content);;
        Multipart part = new MimeMultipart();


        File f = new File("ABC.pdf");
        String s = f.getAbsolutePath();

        System.out.printf(s);

        DataSource source = new FileDataSource(s);
        body.setDataHandler(new DataHandler(source));
        body.setFileName("ABC Bill");
        part.addBodyPart(body);

        message.setContent(part);
        System.out.printf(s);
        Transport.send(message);

        System.out.printf(s);