Java - 使用javax.mail库更改电子邮件附件的名称

时间:2015-07-29 19:17:54

标签: java email attachment javax.mail

这是我目前的代码。它正确发送带有附件的电子邮件,但发送的附件的文件名是我计算机上文件的完整路径。我希望它显示为文件名(即“name_of_file.zip”而不是“/Users/MyUser/Desktop/name_of_file.zip”)。有没有办法做到这一点?

    public void sendMailWithAttachments () {
    Properties props = new Properties();
     props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }});


    String msgBody = "Body of email";
    String fileAttachment = "/Users/MyUser/Desktop/name_of_file.zip";

    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("me@email.com"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress("person@email.com"));
        msg.setSubject("Email Subject!");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(msgBody);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileAttachment);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(fileAttachment);
        multipart.addBodyPart(messageBodyPart);

        msg.setContent(multipart);

        Transport.send(msg);
    } catch (AddressException e) {
        System.out.println(e);
    } catch (MessagingException e) {
        System.out.println(e);
    }
}

1 个答案:

答案 0 :(得分:7)

变化:     messageBodyPart.setFileName(fileAttachment);

于:     messageBodyPart.setFileName(new File(fileAttachment).getName());