Error package javax mail does not exist

I have copies mail.jar and activation.jar in the classpath directory as instructed, then try to compile but got the below error: package javax.mail does not exist please help. G:CRD>javac SendM...

I have copies mail.jar and activation.jar in the classpath directory as instructed, then try to compile but got the below error: package javax.mail does not exist

please help.

G:CRD>javac SendMailBean.java

SendMailBean.java:22: package javax.mail does not exist
import javax.mail.*; //JavaMail packages
^
SendMailBean.java:23: package javax.mail.internet does not exist
import javax.mail.internet.*; //JavaMail Internet packages
^
SendMailBean.java:43: cannot resolve symbol
symbol : class Session
location: class SendMailBean
Session l_session = Session.getDefaultInstance(l_props, null);
^
SendMailBean.java:43: cannot resolve symbol
symbol : variable Session
location: class SendMailBean
Session l_session = Session.getDefaultInstance(l_props, null);
^
SendMailBean.java:48: cannot resolve symbol
symbol : class MimeMessage
location: class SendMailBean
MimeMessage l_msg = new MimeMessage(l_session); // Create a New message
^
SendMailBean.java:48: cannot resolve symbol
symbol : class MimeMessage
location: class SendMailBean
MimeMessage l_msg = new MimeMessage(l_session); // Create a New message
^
SendMailBean.java:50: cannot resolve symbol
symbol : class InternetAddress
location: class SendMailBean
l_msg.setFrom(new InternetAddress(p_from)); // Set the From address
^
SendMailBean.java:53: package Message does not exist
l_msg.setRecipients(Message.RecipientType.TO,
^
SendMailBean.java:54: cannot resolve symbol
symbol : variable InternetAddress
location: class SendMailBean
InternetAddress.parse(p_to, false));
^
SendMailBean.java:57: package Message does not exist
l_msg.setRecipients(Message.RecipientType.CC,
^
SendMailBean.java:58: cannot resolve symbol
symbol : variable InternetAddress
location: class SendMailBean
InternetAddress.parse(p_cc, false));
^
SendMailBean.java:62: package Message does not exist
l_msg.setRecipients(Message.RecipientType.BCC,
^
SendMailBean.java:63: cannot resolve symbol
symbol : variable InternetAddress
location: class SendMailBean
InternetAddress.parse(p_bcc, false));
^
SendMailBean.java:68: cannot resolve symbol
symbol : class MimeBodyPart
location: class SendMailBean
MimeBodyPart l_mbp = new MimeBodyPart();
^
SendMailBean.java:68: cannot resolve symbol
symbol : class MimeBodyPart
location: class SendMailBean
MimeBodyPart l_mbp = new MimeBodyPart();
^
SendMailBean.java:72: cannot resolve symbol
symbol : class Multipart
location: class SendMailBean
Multipart l_mp = new MimeMultipart();
^
SendMailBean.java:72: cannot resolve symbol
symbol : class MimeMultipart
location: class SendMailBean
Multipart l_mp = new MimeMultipart();
^
SendMailBean.java:83: cannot resolve symbol
symbol : variable Transport
location: class SendMailBean
Transport.send(l_msg);
^
SendMailBean.java:98: cannot resolve symbol
symbol : class MessagingException
location: class SendMailBean
} catch (MessagingException mex) { // Trap the MessagingException Error
^
19 errors

When I compile a simple code that has the following 2 import statements:

import javax.mail.*

import javax.mail.internet.*

I get the following message:

package javax.mail does not exist

package javax.mail.internet does not exist

Why do I get this error?

Here is the code I have:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

class tester {
 public static void main(String args[]) {
   Properties props = new Properties();
   props.put("mail.smtp.com" , "smtp.gmail.com");
   Session session  = Session.getDefaultInstance( props , null);
   String to = "[email protected]";
   String from = "[email protected]";
   String subject = "Testing...";
   Message msg = new MimeMessage(session);
    try {
      msg.setFrom(new InternetAddress(from));
      msg.setRecipient(Message.RecipientType.TO , new InternetAddress(to));
      msg.setSubject(subject);
      msg.setText("Working fine..!");
    }  catch(Exception exc) {
       }
 }
}

13 Answers

You need to download the JavaMail API, and put the relevant jar files in your classpath.

Download javax.mail.jar and add it to your project using the following steps:

  1. Extract the mail.jar file
  2. Right click the project node (JavaMail), click Properties to change properties of the project
  3. Now go to Libraries Tab
  4. Click on Add JAR/Folder Button. A window opens up.
  5. Browse to the location where you have unzipped your Mail.jar
  6. Press ok
  7. Compile your program to check whether the JAR files have been successfully included

If using maven, just add to your pom.xml:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.5.0-b01</version>
</dependency>

Of course, you need to check the current version.

You need the javax.mail.jar library.
Download it from the Java EE JavaMail GitHub page and add it to your IntelliJ project:

  1. Download javax.mail.jar
  2. Navigate to File > Project Structure...
  3. Go to the Libraries tab
  4. Click on the + button (Add New Project Library)
  5. Browse to the javax.mail.jar file
  6. Click OK to apply the changes

For anyone still looking to use the aforementioned IMAP library but need to use gradle, simply add this line to your modules gradle file (not the main gradle file)

compile group: 'javax.mail', name: 'mail', version: '1.4.1'

The links to download the .jar file were dead for me, so had to go with an alternate route.

Hope this helps :)

It might be that you do not have the necessary .jar files that give you access to the Java Mail API. These can be downloaded from here.

You need the javax.mail.jar library. Download it from the https://www.oracle.com/java/technologies/javamail-releases.html and add it to your Eclipse project:

If you are using <module-info.java> then,

  1. Right-click on Project, go to Build Path -> Configure Build Path -> Libraries -> ModulePath -> Add External Jars.
  2. Browse to the javax.mail.jar file
  3. Click «Apply and Close».

Under module-info.java, add this:

module TestApp {
    **requires mail;**
}

you have to set the classpath of your mail.jar and activation.jar file like that:

open the command prompt:

c:user>set classpath=%classpath%;d:jarfilesmail.jar;d:jarfilesactivation.jar;.;

and if u don’t have the both file then please download them here

  1. Download the Java mail jars.

  2. Extract the downloaded file.

  3. Copy the «.jar» file and paste it into ProjectNameWebContentWEB-INFlib folder

  4. Right click on the Project and go to Properties

  5. Select Java Build Path and then select Libraries

  6. Add JARs…

  7. Select the .jar file from ProjectNameWebContentWEB-INFlib and click OK

    that’s all

Had the same issue. Obviously these .jars were included with Java <= v8.x out of the box, but are not anymore. Thus one has to separately download them and place them in the appropriate classpath as highlighted by several folks above. I understand that the new Java is modularized and thus potentially more light-weight (which is certainly a good thing, since the old setup was a monster). On the other hand this — as we can see — breaks lots of old build setups. Since the time to fix these isn’t chargeable to Oracle I guess this made their decision easy…

you need mail.jar and activation.jar to build javamail application

I just resolved this for myself, so hope this helps. My project runs on GlassFish 4, Eclipse MARS, with JDK 1.8 and JavaEE 7.

Firstly, you can find javax.mail.jar in the extracted glassfish folder: glassfish4->glassfish->modules

Next, in Eclipse, Right Click on your project in the explorer and navigate the following: Properties->Java Build Path->Libraries->Add External JARs-> Go to the aforementioned folder to add javax.mail.jar

System details:

Ubuntu 17.10
openjdk version "1.8.0_151"
OpenJDK Runtime Environment (build 1.8.0_151-8u151-b12-0ubuntu0.17.10.2-b12)

I can’t get my java program to run. I don’t know why it won’t find the class. It compiles with the -classpath flag, but doesn’t find the class when running.

$ ls -ltra
total 668
-rw-rw-r-- 1 bvpx bvpx 653275 Jan 19 14:45 javax.mail.jar
drwxr-xr-x 3 bvpx bvpx   4096 Jan 19 14:59 ..
-rw-r--r-- 1 bvpx bvpx    960 Jan 19 15:07 Example.java
drwxr-xr-x 2 bvpx bvpx   4096 Jan 19 15:07 .

Compiling without -classpath does not work (I thought -classpath defaulted to .?)

$ javac Example.java 
Example.java:2: error: package javax.mail does not exist

Specifying the -classpath helps, the program now compiles and produces Example.class:

$ javac -classpath javax.mail.jar Example.java
$ 

Here’s the source code:

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class Example {
    static final int PORT = 587;
    /* ... */

    public static void main(String[] args) throws Exception {
        /* ... */
        Transport transport = session.getTransport();
        try
        {
            System.out.println("Sending...");
            transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);
            transport.sendMessage(msg, msg.getAllRecipients());
            System.out.println("Email sent!");
        }
        catch (Exception ex) {
            System.out.println("Error message: " + ex.getMessage());
        }
    }
}

Running the program produces this error:

$ java -Xdiag -classpath javax.mail.jar Example 
Error: Could not find or load main class Example
java.lang.ClassNotFoundException: Example
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)

Running java without -classpath causes the JNI to not find javax/mail even though it’s in the directory.

$ java -Xdiag Example 
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/Address
    at java.lang.Class.getDeclaredMethods0(Native Method)

Why can’t java find the Example class?

Solution:

You seem to be missing some fundamental concepts here.

The classpath gives a list of directories and JAR files to search for needed classes. When trying to load a class foo.bar.MyClass that is not part of the standard library, the default classloader will look for it in each classpath element in turn, in order, until it finds the class or runs out of elements.

Note well, however, that it searches by fully-qualified name. For classpath entries that are directories, that means that it looks for foo/bar/MyClass.class relative to the directory. For classpath entries that are JAR files, it looks for foo/bar/MyClass.class relative to the root of the JAR. Classes that belong to the unnamed default package are a little special, or so it may seem, because their class files (e.g. InDefaultPackage.class) are expected to be located directly in the root of the designated JAR or directly in the specified directory.

Compiling without -classpath does not work (I thought -classpath
defaulted to .?)

$ javac Example.java 
Example.java:2: error: package javax.mail does not exist

The classpath does default to .. This is the name of a directory, so when searching it for classes in, say, the javax.mail package, it looks for a subdirectory javax/mail, and if that is found, it examines the class files within. Note that it does not descend into JAR files it discovers in the directory tree. It looks only in those JARs explicitly named in the classpath.

The error message is telling you that javac didn’t find any classes at all from the javax.mail package. You could have solved it either by specifying the JAR in the compilation classpath (as ultimately you did) or by unpacking the JAR in the current directory.

Specifying the -classpath helps, the program now compiles and produces
Example.class:

$ javac -classpath javax.mail.jar Example.java
$

Note that the compiler will store the classfile in a directory structure corresponding to its package, just where the java command will look for it.

Running the program produces this error:

$ java -Xdiag -classpath javax.mail.jar Example 
Error: Could not find or load main class Example
java.lang.ClassNotFoundException: Example
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)

You clarified in your answer that you solved this problem by removing a package statement from Example.java. That’s ok, but it doesn’t really explain the problem, which is that java expects you to give it the fully-qualified name of the class. That includes the package name if the class is in a named package. Thus, if Example.java contained this package statement:

package com.my;

then the class name you would need to specify to java would be com.my.Example. You specified just Example, which designates a class named “Example” in the default package, and your solution to the class not found problem was to move your class into the default package.

Note also that it is conventional and helpful to lay out your Java source files, too, in a directory structure matching their package structure. Thus, the source file for class com.my.Example would conventionally be located in com/my/Example.java. The Java compiler will rely on this scheme to locate sources for classes that it does not find.

Running java without -classpath causes the JNI to not find
javax/mail even though it’s in the directory.

$ java -Xdiag Example 
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/Address
    at java.lang.Class.getDeclaredMethods0(Native Method)

No, javax/mail/Address was not in the directory. It was in a JAR file in the directory. That’s not at all the same thing, and the difference is significant.

Я использую класс с именем emailer для отправки электронной почты из java-приложения,
я использую нетбинс 6.9.1 и я использую J2SE, я загрузил javamail api и добавил банку в classpath а также положить его в src для нетбинс.

Netbeans выдает ошибку Package javax.mail does not exist а я не знаю почему? Как я чувствую, я сделал все правильно, вот код

import java.util.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.*;
import javax.mail.internet.*;

/**
* Simple demonstration of using the javax.mail API.
*
* Run from the command line. Please edit the implementation
* to use correct email addresses and host name.
*/
public final class Emailer {

  public static void main( String... aArguments ){
    Emailer emailer = new Emailer();
        try {

            emailer.sendEmail("fromblah@blah.com", "toblah@blah.com", "Testing 1-2-3", "blah blah blah");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex);
        }
   }


  public void sendEmail(String aFromEmailAddr, String aToEmailAddr,
    String aSubject, String aBody) throws ClassNotFoundException
  {
      Class.forName("javax.mail");

    Session session = Session.getDefaultInstance( fMailServerConfig, null );
    MimeMessage message = new MimeMessage( session );
    try {

      message.addRecipient(
        Message.RecipientType.TO, new InternetAddress(aToEmailAddr)
      );
      message.setSubject( aSubject );
      message.setText( aBody );
      Transport.send( message );
    }
    catch (MessagingException ex){
      System.err.println("Cannot send email. " + ex);
    }
  }


  public static void refreshConfig() {
    fMailServerConfig.clear();
    fetchConfig();
  }



  private static Properties fMailServerConfig = new Properties();

  static {
    fetchConfig();
  }


  private static void fetchConfig() {
    InputStream input = null;
    try {

      input = new FileInputStream( "C:\Temp\MyMailServer.txt" );
      fMailServerConfig.load( input );
    }
    catch ( IOException ex ){
      System.err.println("Cannot open and load mail server properties file.");
    }
    finally {
      try {
        if ( input != null ) input.close();
      }
      catch ( IOException ex ){
        System.err.println( "Cannot close mail server properties file." );
      }
    }
  }
}

Как решить эту проблему?

Понравилась статья? Поделить с друзьями:
  • Error permission denied apply2files usr local lib docker cli plugins
  • Error overloaded operator must be a unary or binary operator has 3 parameters
  • Error perl execution failed
  • Error overloaded function with no contextual type information
  • Error performing query перевод