繁体   English   中英

使用Java发送带有附件的电子邮件

[英]Sending EMail with Attachment with 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);
    }
}

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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