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:


 import java.util.Properties;   
 import javax.mail.*;   
 import javax.mail.internet.*;   
 public class EmailSender {  
    private final String smtpServer;  
    private final int smtpPort;  
    private final String smtpUserName;  
    private final String smtpPassword;  
    public EmailSender(String smtpServer, int smtpPort, String smtpUserName, String smtpPassword) {  
    super();  
           this.smtpServer = smtpServer;  
           this.smtpPort = smtpPort;  
           this.smtpUserName = smtpUserName;  
           this.smtpPassword = smtpPassword;  
      }  
      public boolean sendEmail(String senderEmail, String[] recipientsTo, String[] recipientsCc, String emailSubject, String emailMessage){  
           System.out.println("*** Sending email ***");  
           if(!validateServerInfo()){  
                System.err.println("Aborting!");  
                return false;  
           }  
           Properties props = new Properties();  
           props.put("mail.smtp.host", smtpServer);  
           props.put("mail.smtp.socketFactory.port", smtpPort);  
           props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  
           props.put("mail.smtp.auth", "true");  
           props.put("mail.smtp.port", String.valueOf(smtpPort));  
           Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {  
                protected PasswordAuthentication getPasswordAuthentication() {  
                     return new PasswordAuthentication(smtpUserName, smtpPassword);  
                }  
           });  
           try {  
                Message message = new MimeMessage(session);  
                message.setFrom(new InternetAddress(senderEmail));  
                String toAddresses = ""; // Used only for providing feedback 
                String ccAddresses = ""; // Used only for providing feedback  
                for(String toRecipient : recipientsTo){  
                     toAddresses += toRecipient + " ";  
                     message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(toRecipient));  
                }  
                for(String ccRecipient : recipientsCc){  
                     ccAddresses += ccRecipient + " ";   
                     message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(ccRecipient));  
                }  
                System.out.println("\tTO: " + toAddresses.trim());  
                System.out.println("\tCC: " + ccAddresses.trim());  
                System.out.println("\tSUBJECT: " + emailSubject);  
                System.out.println("== MESSAGE ==\n" + emailMessage);  
                System.out.println("=============");  
                message.setSubject(emailSubject);  
                message.setText(emailMessage);  
                Transport.send(message);  
                System.out.println("Done!");  
           } catch (MessagingException e) {  
                System.err.println("ERROR: MessagingException: " + e.getMessage());  
                return false;  
           }  
           return true;  
      }  
      private boolean validateServerInfo(){  
           boolean res = true;  
           if(smtpServer ==null || smtpServer.trim().length()==0){  
                System.err.println("No SMTP server was provided.");  
                res = false;  
           }  
           if(smtpPort > 65535 || smtpPort < 0){  
                System.err.println("The port number is invalid.");  
                res = false;  
           }  
           if(smtpUserName ==null || smtpUserName.trim().length()==0){  
                System.err.println("No username was given.");  
                res = false;  
           }  
           // The password could actually be blank so we don't check  
           return res;  
      }  
 }  

No comments:

Post a comment