Search code examples
javacommand-linejarclasspath

Can't run java application with jar dependency: Could not find or load main class


My code runs fine in my IDE, and I have the javax.mail.jar set as a dependency, and my code runs fine.

Except, I need to use

Console console = System.console();

and this does not work within IDE.

So, I am trying to compile my code and run it via the terminal. I can compile, although, when running my code it returns the error:

Error: Could not find or load main class Main

This is what I do to compile:

javac -cp "./javax.mail.jar" Main.java

Then to run it:

java -cp "./javax.mail.jar" Main

But, I get the error:

Could not find or load main class Main

This is my full code:

package com.company;

import java.io.IOException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Main {
public static void main(String[] args) throws IOException {


    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("[email protected]","pass");
                }
            });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
        message.setSubject("JavaMail");
        message.setText("Hi," + "\n\n This is a test");

        Transport.send(message);

        System.out.println("Sent!");


    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}


}

EDIT:

Also, I've tried running from parent directory (This has my com folder in and the java.mail.jar):

java -cp "./javax.mail.jar;." com.company.Main

But I get this:

Error: Could not find or load main class com.company.Main


Solution

  • You shall compile it from parent folder of com, by:

    javac -cp "./javax.mail.jar:." com/company/Main.java
    

    And then run by

    java -cp "./javax.mail.jar:." com.company.Main