title: Java - Change the name of email attachment using javax.mail library
body: <p>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?</p>
  
  <p><code> </p>
  
  <pre>    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);
      }
  }
  </code></pre>
  
  <p></p>