Thursday 11 August 2011

Sending emails via Gmail (and others) in Java.

The following class will send emails from a java program. It definitely works on Gmail accounts and if you know the settings it should work on others as well. Keep in mind that it needs the javax.mail jar in your classpath.

You can use it like this:

private static void sendEmail(){  
     String[] toRecipients = {"he@it.com", "you@yes.you", "hey@there.com"};  
     String[] ccRecipients = {"this@concerns.you", "and@you.too"};  
     EmailSender es = new EmailSender("smtp.gmail.com", 465, "myEmail@gmail.com", "myPassword");  
     boolean res = es.sendEmail("myEmail@gmail.com", toRecipients, ccRecipients, "Hey guys!", "I can automate email sending now!");  
     if(res){  
          System.out.println("Woohoo!");  
     } else {  
          System.err.println("Hmmmm... Something went wrong...");  
     }  
}  
And here is the class: