0

i have the following code to send an email with attachment. The problem is, that the attachment, which is a simple text file, is empty. But the file isn't. Just in the email it is. The text is showing correctly. No error codes.

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);
    }
}
user3515460
  • 159
  • 1
  • 13
  • This seem to already been asked : http://stackoverflow.com/questions/16117365/sending-mail-attachment-using-java – Chris Apr 13 '16 at 13:33
  • and a little google search would have return you that tutorial and probably took less time than posting here : http://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm – Chris Apr 13 '16 at 13:34
  • This could be found easly on google, next time try to search. – Severiano Apr 13 '16 at 13:55

1 Answers1

1

try this

 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 );
Akceptor
  • 1,914
  • 3
  • 26
  • 31