Saturday 21 February 2015

How to send Email to multiple recipients with multiple text messages via SMTP with javaMail

Here i am going to showing how to Send email in java using Gmail SMTP and JavaMail API.

I have used one dependency jar "javax.mail.jar"


package com.mail.system;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailTest {

public static void main(String[] args) {

String mailSmtpHost = "smtp.gmail.com";

String[] mailTo = {"mail1@gmail.com","mail2@hotmail.com"};  
String mailCc = "ccMail@rediffmail.com";
String mailFrom = "fromMail@gmail.com";
String mailSubject = "Email from Java";
String[] mailText = {"send email for gmail domain","send email to hotmail domain"};

for (int i = 0; i < mailTo.length; i++) {

sendEmail(mailTo[i], mailCc, mailFrom, mailSubject, mailText[i], mailSmtpHost);
}
}

public static void sendEmail(String to, String cc, String from, String subject, String text, String smtpHost) {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
//Session emailSession = Session.getDefaultInstance(properties);

// If you want to use SSL
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");

Session emailSession = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "fromMail@gmail.com";        
String password = "password";
return new PasswordAuthentication(username,password);

}
});

Message emailMessage = new MimeMessage(emailSession);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
emailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
emailMessage.setText(text);

emailSession.setDebug(true);
Transport transport = emailSession.getTransport("smtp");
transport.send(emailMessage);
System.out.println("Mail successfully Send to ....."+to);
transport.close();
System.out.println("\n");
System.out.println("Transport Session Close .....");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}


No comments:

Post a Comment