使用Java-Mail发送附件无法正常工作

时间:2016-07-07 08:47:57

标签: java

我发送带附件的电子邮件。邮件的正文是正确的,但附件是空的。附件的大小正在显示。那有什么不对?

    // Create the message part
    BodyPart messageBodyPart = new MimeBodyPart();

    // Now set the actual message
    messageBodyPart.setText(
            "Prozess vom " + new SimpleDateFormat("dd.MM.yyyy").format(new Date()) + " erfolgreich beendet");

    // Create a multipar message
    Multipart multipart = new MimeMultipart();


    // Part two is attachment
    BodyPart attachement = new MimeBodyPart();
    File fi = new File("C:" + File.separator + "Logdatei_Auto" + File.separator + "logdatei.txt");
    String filename = fi.getAbsolutePath();
    String name = fi.getName();
    javax.activation.DataSource source = new FileDataSource(filename);
    attachement.setDataHandler(new DataHandler(source));
    attachement.setFileName(name);
    multipart.addBodyPart(messageBodyPart);
    multipart.addBodyPart(attachement);

    // Send the complete message parts
    message.setContent(multipart);


    // Send message
    Transport.send(message);

更新

最后它可以使用以下代码:

File filename = new File("logdatei.pdf");


    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    Authenticator auth = new SMTPAuthenticator();
    Session mailSession = Session.getDefaultInstance(props, auth);
    // Create a default MimeMessage object.
    // Create a default MimeMessage object.
     try {
            MimeMessage message = new MimeMessage(mailSession);
            message.setFrom(new InternetAddress("*******"));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress("*******"));
            message.setSubject("Test");
            message.setSentDate(new Date());

            //
            // Set the email message text.
            //
            MimeBodyPart messagePart = new MimeBodyPart();
            messagePart.setText("Blah...");

            //
            // Set the email attachment file
            //
            MimeBodyPart attachmentPart = new MimeBodyPart();
            FileDataSource fileDataSource = new FileDataSource(filename) {
                @Override
                public String getContentType() {
                    return "application/octet-stream";
                }
            };
            attachmentPart.setDataHandler(new DataHandler(fileDataSource));
            attachmentPart.setFileName(filename.getName());

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messagePart);
            multipart.addBodyPart(attachmentPart);

            message.setContent(multipart);

            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

谢谢@ all

1 个答案:

答案 0 :(得分:0)

尝试以下代码

MimeMultipart multipart = new MimeMultipart("mixed");
MimeBodyPart attachment = new MimeBodyPart();
attachment.setDisposition(Part.ATTACHMENT);
attachment.setDataHandler(new DataHandler(new FileDataSource(file)));
attachment.setFileName(file.getName());
multipart .addBodyPart(attachment);
message.setContent(multipart);

我认为你错过了

attachment.setDisposition(Part.ATTACHMENT);

所以基本上将Disposition添加为Part.ATTACHMENT表示此部分应作为附件显示。

更新

在代码下方发送带附件的电子邮件:

        try
        {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("fromEmailAddress"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("toEmailAddress"));
            message.setSubject("message with attachment");
            message.setContent("Hi", "text/plain; charset=UTF-8");


            File file = File.createTempFile("test", ".csv");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8").newEncoder());
            PrintWriter writer = new PrintWriter(outputStreamWriter);
            writer.println("\u20ac;");
            writer.println("€");
            writer.flush();

            MimeMultipart rootMultipart = new MimeMultipart("mixed");
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setDisposition(Part.ATTACHMENT);
            bodyPart.setDataHandler(new DataHandler(new FileDataSource(file)));
            bodyPart.setFileName(file.getName());
            rootMultipart.addBodyPart(bodyPart);
            message.setContent(rootMultipart);

            Transport.send(message);

            writer.close();
            file.delete();
            System.out.println("Message sent successfully!");

        }
        catch (MessagingException e)
        {
            throw new RuntimeException(e);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }