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); } }
Change:
messageBodyPart.setFileName(fileAttachment);
to:
messageBodyPart.setFileName(new File(fileAttachment).getName());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With