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

public class SendMailTLS {

	public static void main(String[] args) {
		String host = "smtp.gmail.com";
		int port = 587;
		String username = "avdhoot.patel@gmail.com";
		String password = "password";

		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");

		Session session = Session.getInstance(props);

		try {

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

			Transport transport = session.getTransport("smtp");
                        
			transport.connect(host,port,username,password);

			Transport.send(message);

			System.out.println("Done");

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

this code throws runtime exception though i am providing the correct password. Please Don't mind in this code i provide the incorrect password

Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at SendMailTLS.main(SendMailTLS.java:42)
Caused by: javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Nevermind that. See the link anyway.

See this.

In NetBeans6.9 project the class path for both has been set

And it obviously has nothing to do with the classpath (I never said, or even hinted that it did) or you would be getting a ClassNotFoundException, of course.

See that link.

@patel.ajay82

You need to read Authenticator paragraph for your reference and here you missed mail.smtp.host:host entry.

class MyAuth extends Authenticator
{
     protected PasswordAuthentication getPasswordAuthentication()
      {
         return new PasswordAuthentication("username","password"); 
      } 
}
public static void main(String[] args) {
		......
                ......
		Properties props = new Properties();
                props.put("mail.smtp.host", host);

		......
                Authenticator auth = new MyAuth();
                Session session = Session.getInstance(props, auth);
                .....

Hope it helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.