简体   繁体   中英

Sending EMail with Attachment with Java

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);
    }
}

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM