Search code examples
javamailto

Java mailto Illegal character colon?


im trying to send an email with an attachment, but it keeps saying:

 Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Illegal character in opaque part at index 64: mailto:[email protected]?subject=ThePDFFile&attachment=C:\Users\Rascal\AppData\Local\Temp\FreelancerList-16-12-2014_09-227568200505392670736.doc

Java Code:

Desktop desktop = Desktop.getDesktop(); 
        String message = "mailto:[email protected]?subject=ThePDFFile&attachment=\""+path; 
        URLEncoder.encode(message, "UTF-8");
        URI uri = URI.create(message); 
        desktop.mail(uri);    

Should be the colon right? But why???


Solution

  • You're calling URLEncoder.encode, but ignoring the result. I suspect you were trying to achieve something like this:

    String encoded = URLEncoder.encode(message, "UTF-8");
    URI uri = URI.create(encoded);
    

    ... although at that point you'll have encoded the colon after the mailto part as well. I suspect you really want something like:

    String query = "subject=ThePDFFile&attachment=\""+path;
    String prefix = "mailto:[email protected]?";
    URI uri = URI.create(prefix + URLEncoder.encode(query, "UTF-8"));
    

    Or even encoding just the values:

    String query = "subject=" + URLEncoder.encode(subject, "UTF-8");
        + "&attachment=" + URLEncoder.encode(path, "UTF-8"));
    URI uri = URI.create("mailto:[email protected]?" + query);
    

    ... or create the URI from the various different parts separately, of course.