Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Change the name of email attachment using javax.mail library

Here is my current code. It correctly sends an email with an attachment, but the file name of the attachment sent is the full path to the file on my computer. I want it to show up just as the file name (i.e. "name_of_file.zip" as opposed to "/Users/MyUser/Desktop/name_of_file.zip"). Is there a way to do this?

    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("[email protected]"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
        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);
    }
}

like image 482
OnlyDean Avatar asked Jan 07 '23 21:01

OnlyDean


1 Answers

Change: messageBodyPart.setFileName(fileAttachment);

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

like image 69
Peter Kalef ' DidiSoft Avatar answered Jan 31 '23 05:01

Peter Kalef ' DidiSoft