2

I am trying to create a simple javamail App which can handle attachments,but it is showing "java.io.FileNotFoundException: fileName" whenever i send an email. There is no problem in uploading file i have verified,but it is failing to extract absolute path of the uploaded file.I am using an html form to send multipart form-data. Given below is my java code for it:

[Edited]MailApp.java:

@WebServlet("/EmailSendingServlet")
@MultipartConfig(fileSizeThreshold=58576, maxFileSize=20848820, maxRequestSize=418018841)

public class MailApp extends HttpServlet {
private String host;
private String port;

private static final String SAVE_DIR = "uploadFiles";

public void init() {
    host = "smtp.gmail.com";
    port = "587";    }

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String recipient = null;
    String subject = null;
    String content = null;
    String user = null;
    String pass = null;
    String fileName = null;

 // gets absolute path of the web application
    String appPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    String savePath = appPath + File.separator + SAVE_DIR;

    // creates the save directory if it does not exists
    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }

    for( Part p : request.getParts() ) {
        if( "uploaded_file".equals(p.getName()) ) {
             fileName = extractFileName(p);
            // refines the fileName in case it is an absolute path
            fileName = new File(fileName).getName();
            p.write(savePath + File.separator + fileName);
        }
       else if( "recipient".equals(p.getName()) ) {recipient = request.getParameter("recipient");}
       else if( "subject".equals(p.getName()) ) {subject = request.getParameter("subject");}
        if( "content".equals(p.getName()) ) {content = request.getParameter("content");}
       else if( "user".equals(p.getName()) ) {user = request.getParameter("user");}
       else if( "pass".equals(p.getName()) ) {pass =request.getParameter("pass");}

    }
String resultMessage = "";


    try {            
        SendMail.sendEmail(host, port, user, pass, recipient, subject, content, fileName);
        resultMessage = "The e-mail was sent successfully";
    } catch (Exception ex) {
        ex.printStackTrace();
        resultMessage = "There were an error: " + ex.getMessage();
    } 
    finally {
        request.setAttribute("Message", resultMessage);
        getServletContext().getRequestDispatcher("/iml.jsp").forward(
                request, response);
    }
}
private String extractFileName(Part part) {
    String contentDisp = part.getHeader("content-disposition");
    String[] items = contentDisp.split(";");
    for (String s : items) {
        if (s.trim().startsWith("filename")) {
            return s.substring(s.indexOf("=") + 2, s.length()-1);
        }
    }
    return "";
}}

SendMail.java:

public class SendMail 
{ 
   public static void sendEmail(String host, String port,
            final String userName, final String password, String toAddress,
            String subject, String message,String fileName) throws AddressException,
            MessagingException {


        // sets SMTP server properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        // creates a new session with an authenticator
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        };

        Session session = Session.getInstance(properties, auth);

        // creates a new e-mail message
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(userName));
        InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(message, "text/html");

        // creates multi-part
        Multipart multipart = new MimeMultipart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(fileName);
        multipart.addBodyPart(messageBodyPart);


        // sets the multi-part as e-mail's content
        msg.setContent(multipart);

   try{     // sends the e-mail
        Transport.send(msg);
   }
   catch (Exception ex) {
       ex.printStackTrace();
   }
}
}

please help me resolve it

pmgowda
  • 33
  • 6
  • As far as i know `Paths.get(filePart.getSubmittedFileName()).getFileName().toString();` is gives you exact file name and `Paths.get(filePart.getSubmittedFileName())` gives file path. Lets try without `.getFileName.toString()`. – newuserua_ext Jan 02 '17 at 11:32
  • Used `Paths.get(filePart.getSubmittedFileName()).toString();` , but still getting only file name. – pmgowda Jan 03 '17 at 05:57
  • Just stop using `getRealPath()`. – BalusC Jan 03 '17 at 07:56
  • I have verified there is no problem uploading file, the problem appears when am trying the access the same file while sending – pmgowda Jan 03 '17 at 09:09

2 Answers2

0
  1. You need to create a directory to save the uploaded file

  2. you need to create a full path for the file

  3. you nee to write the file uploaded to the file you save by using:

    filePart.write(FULL_FILE_PATH);
    
  4. You can follow this link
lonchu
  • 21
  • 6
0

Okay, I could be wrong here... While saving ( writing ) you are doing

p.write(savePath + File.separator + fileName);

But while calling "sendEmail" you are sending only "fileName", should't it be "savePath + File.separator + fileName" instead ?

  • tried it, still getting same exception. I think its failing to extract absolute path. – pmgowda Jan 03 '17 at 05:51
  • Okay, check the permissions as well, is "SAVE_DIR" and the file getting created ? – anupkholgade Jan 03 '17 at 06:07
  • Yes it getting created , here is the path where files are being stored "E:\java WS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Mwa\\uploadFiles". Ithink the problem is with two '\' before uploadfiles? – pmgowda Jan 03 '17 at 06:29
  • Can you please check this thread, and confirm something simillar is not happening i your case too "http://stackoverflow.com/questions/13063773/upload-a-file-in-a-servlet". – anupkholgade Jan 03 '17 at 08:06
  • upload is working. – pmgowda Jan 03 '17 at 09:11