Reputation: 159
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("[email protected]", "Muster AG"));
msg.setRecipients(Message.RecipientType.TO, "[email protected]");
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);
}
}
Upvotes: 0
Views: 117
Reputation: 1932
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 );
Upvotes: 1