JavaFx sending a temporary excel file as an attachment in mail

I want to send a excel file as an attachment in mail
When i use the a physical file everything is good but when i use it as a temporary file i got this exception

javax.mail.MessagingException: IOException while sending message;        
java.io.FileNotFoundException: 2019-03-02.xls (Le fichier spécifié est introuvable)

when creating the temporary file the following code is used :

//....
    try {//create temp file here
            file = File.createTempFile(today,".xlsx");
        } catch (IOException ex) {
            Logger.getLogger(Writer.class.getName()).log(Level.SEVERE, null, ex);
        }
            try (FileOutputStream fileOut = new FileOutputStream(file)) {
                workbook.write(fileOut);
//.....

but when i use a normal file like this it works very fine :

try (FileOutputStream fileOut = new FileOutputStream(today+".xlsx")) {
            workbook.write(fileOut);

any solutions ?

or any suggestions how to send an excel file without saving it ?

EDIT : here is the full exception

javax.mail.MessagingException: IOException while sending message;
  nested exception is:
    java.io.FileNotFoundException: 2019-03-02.xls (Le fichier spécifié est introuvable)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:625)
    at rapport.rapportc.sendMail(rapportc.java:113)
    at rapport.rapportc.envoyer(rapportc.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8413)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: 2019-03-02.xls (Le fichier spécifié est introuvable)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at javax.activation.FileDataSource.getInputStream(FileDataSource.java:97)
    at javax.activation.DataHandler.writeTo(DataHandler.java:305)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:845)
    at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:361)
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:85)
    at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:889)
    at javax.activation.DataHandler.writeTo(DataHandler.java:317)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
    at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1683)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:585)
    ... 60 more

EDIT2 : here is the function i use to send an email with attachment

private void sendMail(){

        try{
        String host ="smtp.gmail.com" ;
        String user = "[email protected]";
        String pass = "pwd";
        String to = "[email protected]";
        String from = "[email protected]";
        String subject = "sending day : "+today; // today is a string variable for today's date
        String messageText = "msg";
        boolean sessionDebug = false;

        Properties props = System.getProperties();

        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.required", "true");

        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        Session mailSession = Session.getDefaultInstance(props, null);
        mailSession.setDebug(sessionDebug);
        Message msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = {new InternetAddress(to)};
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject); msg.setSentDate(new Date());
        msg.setText(messageText);
        Multipart emailContent = new MimeMultipart();
        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText("");
        MimeBodyPart excelAttach = new MimeBodyPart();
        String path = today+".xls"; // here where i put the excel file to be send
        excelAttach.attachFile(path);
        emailContent.addBodyPart(textBodyPart);
        emailContent.addBodyPart(excelAttach);
        msg.setContent(emailContent);

        Transport transport=mailSession.getTransport("smtp");
        transport.connect(host, user, pass);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        System.out.println("message send successfully");

    }catch(IOException | MessagingException ex)
    {
        alert.alert.showErrorMessage(ex);
        return;
    }
}

Ps : when i send a physical file everything works fine

i want to send the excel file without saving it either with temporary file or another way !

Answer

You can get a more informative exception message if you change this:

excelAttach.attachFile(path);

to this:

excelAttach.attachFile(new File(path).getAbsolutePath());

The problem is that you have made two incorrect assumptions about the behavior of File.createTempFile.

All operating systems create a temporary file using a set of random characters, to guarantee that the file is unique. When you do file = File.createTempFile(today, ".xlsx"), you are not creating a file named 2019-03-02.xls, but rather a file with a name like /tmp/2019-03-02jxl9BZ.xls. So, when you attach 2019-03-02.xls, you are attaching a nonexistent file, which is what the exception is telling you.

The second problem is that you are passing a relative filename. A relative filename is always resolved relative to the current directory of the Java process. This means 2019-03-02.xls is the same as /home/vgr/2019-03-02.xls, if you happen to be running from the /home/vgr directory. But temporary files are never created in that location, so, again, you are trying to attach a file that doesn’t exist. (Relative files are not a Java concept; they have been a fundamental part of operating systems for decades.)

The solution is to retain file in a field (if you aren’t doing so already), and pass that to the attachFile method:

excelAttach.attachFile(file);

Leave a Reply

Your email address will not be published. Required fields are marked *