Email Notification

EmailNotification

//activation-1.1.1.jar and mail-1.4.7.jar
/*when you execute 1 st time we will get AuthenticationFailedException
do the following steps to resolve it

we will get mail from google with subject
"Review blocked sign-in attempt"

open that mail in that an link with name
"allowing access to less secure apps"
click on it

Then it will an Sliding radio button
Allow less secure apps :ON

we you can execute you will get mail*/


import java.util.ArrayList;
import java.util.Properties;
import javax.mail.Address;
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 SendHTMLEmail2{

public static void main(String[] args) {
final String host="smtp.gmail.com";
final String port="25";
final String username = "mail2java@gmail.com";
final String password = "XXX";
final String toEmail = "rajesh@gmail.com";
final String toAddress="Testing Email";
final String body="Dear Mail Crawler,"+ "\n\n No spam to my email, please!";


ArrayList<String> emailList2 = new ArrayList();
emailList2.add("siva@gmail.com");
emailList2.add("ravedhra@gmail.com");

SendHTMLEmail2.sendEmail(host, port, username, password, toEmail, toAddress, body,null);
}

public static void sendEmail(String host,String port,String username,String password,String toAddress,String subject,String body,ArrayList<String> emailList)
{
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.ssl.enable", "false");
Session session = Session.getInstance(props,
  new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
  });
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
message.setSubject(subject);
message.setText(body);
if(emailList!=null && emailList.size()>0)
message.setRecipients(Message.RecipientType.BCC, getEmailsList(emailList));
message.setHeader("X-Mailer", "Lessor JavaMail");
    message.setSentDate(new java.util.Date());
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}

}
private static Address[] getEmailsList(ArrayList< String > emails) {
  Address[] emaiAddresses = new Address[emails.size()];
  for (int i =0;i < emails.size();i++) {
   try {
    emaiAddresses[i] = new InternetAddress(emails.get(i));
   }
   catch (AddressException e) {
    e.printStackTrace();
   }
  }
  return emaiAddresses;
 }

}

No comments:

Post a Comment