1

This is my code for send email in core java.but it cannot work please suggest some solutions.

final String username = "username@gmail.com";
    final String password = "password";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
      });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("username@gmail.com"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("username@gmail.com"));
        message.setSubject("Testing Subject");
        message.setText("Dear Mail Crawler,"
            + "\n\n No spam to my email, please!");

        Transport.send(message);

        System.out.println("Done");

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

I am receiving the following exception when trying to use java mail;

Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
    at javax.mail.Session.initLogger(Session.java:227)
    at javax.mail.Session.<init>(Session.java:212)
    at javax.mail.Session.getInstance(Session.java:248)
    at SendMailTLS.main(SendMailTLS.java:26)
Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    enter code here`at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    enter code here`at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 4 more
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Sriram S
  • 533
  • 3
  • 26

2 Answers2

1

Try "Apache Commons Email" Lib at http://commons.apache.org/proper/commons-email/

Peter Pan
  • 23,476
  • 4
  • 25
  • 43
1

com.sun.mail.util.MailLogger is in JavaMail API which is not included in Java SE.

Try adding this maven dependency or get this jar to classpath

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.5.2</version>
</dependency>

more details on javamail here.

Sheetal Mohan Sharma
  • 2,908
  • 1
  • 23
  • 24