Skip to content
Advertisement

Can’t run java application with .jar dependancy – ‘Error: Could not find or load main class’

So 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’s

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("TestEmail@gmail.com","pass");
                }
            });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("TestEmail@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("TestEmail@gmail.com"));
        message.setSubject("JavaMail");
        message.setText("Hi," + "nn This is a test");

        Transport.send(message);

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


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


}

Edit: Also 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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement