Thursday, October 31, 2013

How to send batch email using Gmail in Java

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 BatchEmailer {

      public static void main(String[] args) {
            Properties props = System.getProperties();
        props.put("mail.smtp.user", "abc@gmail.com");
        props.put("mail.smtp.password", "12345678");
            props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.stmp.sendpartial", "true");
       
        Session session = Session.getDefaultInstance(props);
            Message message = new MimeMessage(session);
           
            try {
                  message.setFrom(new InternetAddress("abc@gmail.com"));

                  String[] toAddress = new String[] { "aaa@aaa.com", "bbb@bbb.com", "ccc@ccc.com" };
                  for (int i = 0; i < toAddress.length; i++) {
                        InternetAddress address = new InternetAddress(toAddress[i]);
                        message.addRecipient(Message.RecipientType.TO, address);
                  }

                  message.setSubject("Batch Email Testing");
                  message.setText("Batch Email Testing 1 2 3");

                  Transport.send(message);
            } catch (MessagingException e) {
                  e.printStackTrace();
            }
      }
}

No comments: