Search code examples
javasessiongmail

how can i send mail using google in core java


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

final String username = "[email protected]";
    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("[email protected]"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("[email protected]"));
        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

Solution

  • 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.