I would like to send emails via Java code. I added in my library the following .JARs: log4j.jar, smtp.jar, mailapi.jar,ctivation.jar. And my Java class looks like this:
import java.util.Properties;
import javax.
mail.*;
import javax.
mail.internet.*;
public class SendEmail
{
public static void main(String [] args)
{
String to = "
[email protected]";
String from = "
[email protected]";
String host = "smtp.gmail.com";
Properties properties = System.getProperties();
properties.setProperty("
mail.smtp.host", host);
properties.setProperty("
mail.smtp.starttls.enable", "true");
properties.setProperty("
mail.smtp.auth", "true");
SmtpAuthenticator authentication = new SmtpAuthenticator();
javax.
mail.Message msg = new MimeMessage(Session
.getInstance(properties, authentication));
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO,
new InternetAddress(to));
msg.setSubject("Subject");
msg.setText("Working fine..!");
System.out.println("fine1 !!");
Transport transport = Session.getDefaultInstance( properties , null).getTransport("smtp");
System.out.println("fine2 !!");
transport.connect("smtp.gmail.com" , 465 , "username", "password");
System.out.println("fine3 !!");
Transport.send(msg);
System.out.println("fine!!");
}
catch(Exception exc) {
System.out.println(exc);
}
}
}
My SmtpAuthenticator class:
import javax.
mail.Authenticator;
import javax.
mail.PasswordAuthentication;
public class SmtpAuthenticator extends Authenticator {
public SmtpAuthenticator() {
super();
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = "user";
String password = "password";
if ((username != null) && (username.length() > 0) && (password != null)
&& (password.length() > 0)) {
return new PasswordAuthentication(username, password);
}
return null;
}
}
When i run my Java application class it prints:
fine1 !!
fine2 !!
And it hangs. How can I get rid of this problem?