使用Java附件发送电子邮件

时间:2016-04-13 13:24:23

标签: java

我有以下代码来发送带附件的电子邮件。问题是,附件是一个简单的文本文件,是空的。但文件不是。 就在电子邮件中。文字显示正确。没有错误代码。

private void emailSenden() throws MessagingException, FileNotFoundException, IOException {

    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.port", "587");

    Authenticator auth = new SMTPAuthenticator();
    Session mailSession = Session.getDefaultInstance(props, auth);

    MimeMessage msg = new MimeMessage(mailSession);
    msg.setFrom(new InternetAddress("xyz@xxx.de", "Muster AG"));
    msg.setRecipients(Message.RecipientType.TO, "abc@aaa.de");
    msg.setSubject("Update erfolgreich.");
    msg.setSentDate(new Date());

    try {
        Multipart mp = new MimeMultipart();

        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText("Update erfolgreich");
        mp.addBodyPart(textPart);

        MimeBodyPart attachFilePart = new MimeBodyPart();
        attachFilePart.attachFile(new File("C:" + File.separator + "log" + File.separator + "logDatei.txt"));
        mp.addBodyPart(attachFilePart);

        msg.setContent(mp);
        msg.saveChanges();
        Transport.send(msg);

        System.out.println("Email gesendet");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

private class SMTPAuthenticator extends javax.mail.Authenticator {
    public PasswordAuthentication getPasswordAuthentication() {
        String username = SMTP_AUTH_USER;
        String password = SMTP_AUTH_PWD;
        return new PasswordAuthentication(username, password);
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个

 attachFilePart = new MimeBodyPart();
 String filename = "c:\log\logDatei.txt";
 DataSource source = new FileDataSource(filename);
 attachFilePart .setDataHandler(new DataHandler(source));
 attachFilePart .setFileName(filename);
 multipart.addBodyPart(attachFilePart );