Sending mail using Java Code

Old code which works before 2 step verification was not  enabled

The below code works if 2 step verification is not enabled

package mailsend;

import java.util.*;

import javax.mail.*;

import javax.mail.internet.*;


public class send {


private static String USER_NAME = "kspriyaece1995";  // GMail user name (just the part before "@gmail.com")

private static String PASSWORD = "******"; // GMail password


private static String RECIPIENT = "khariprasanna2001@gmail.com";


public static void main(String[] args) {

    String from = USER_NAME;

    String pass = PASSWORD;

    String[] to = { RECIPIENT }; // list of recipient email addresses

    String subject = "Java send mail example";

    String body = "hi ....,!";


    sendFromGMail(from, pass, to, subject, body);

}


private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {

    Properties props = System.getProperties();

  String host = "smtp.gmail.com";

    props.put("mail.smtp.starttls.enable", "true");

    props.put("mail.smtp.ssl.trust", host);

    props.put("mail.smtp.user", from);

    props.put("mail.smtp.password", pass);

    props.put("mail.smtp.port", "587");

    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);

    MimeMessage message = new MimeMessage(session);

    try {

        message.setFrom(new InternetAddress(from));

        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses

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

            toAddress[i] = new InternetAddress(to[i]);

        }

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

            message.addRecipient(Message.RecipientType.TO, toAddress[i]);

        }

        message.setSubject(subject);

        message.setText(body);

        Transport transport = session.getTransport("smtp");

        transport.connect(host, from, pass);

        transport.sendMessage(message, message.getAllRecipients());

        transport.close();

    }

    catch (AddressException ae) {

        ae.printStackTrace();

    }

    catch (MessagingException me) {

        me.printStackTrace();

    }

    }

   } 


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

package mailsend;

import java.io.BufferedReader;

import java.io.Console;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.Arrays;

import java.util.List;

import java.util.Properties;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.NoSuchProviderException;

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

public static void main(String[] args) throws NoSuchProviderException {

      // Recipient's email ID needs to be mentioned.

String to = "selvapriya.k@mookambikainfo.com";

    String msg ="Hi "+" "+"spkannan";    

  

/*     final String addressFrom=from;

*/

    Properties props = new Properties();  

    props.setProperty("mail.transport.protocol", "smtp");     

    props.setProperty("mail.host", "smtp.gmail.com");  

    props.put("mail.smtp.auth", "true");  

    props.put("mail.smtp.port", "465");  

    props.put("mail.debug", "true");  

    props.put("mail.smtp.socketFactory.port", "465");  

    props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");  

    props.put("mail.smtp.socketFactory.fallback", "false");

/*        props.put("mail.smtp.starttls.enable", true);    

*/

    Session session = Session.getDefaultInstance(props,  

    new javax.mail.Authenticator() {

       protected PasswordAuthentication getPasswordAuthentication() {  

       return new PasswordAuthentication("kspriyaece1995@gmail.com","AppPassword\n" + 

        "");  

   }  

   });  

   //session.setDebug(true);  

   Transport transport = session.getTransport();  

   InternetAddress addressFrom = null;

try {

addressFrom = new InternetAddress("kspriyaece1995@gmail.com");

} catch (AddressException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}  

   MimeMessage message = new MimeMessage(session);  

   try {

message.setSender( addressFrom);

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}  

   try {

message.setSubject("Test my mail");

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}  

   try {

   message.setSubject("Verification Message");  

/*         message.setContent(msg+"<head><meta charset='utf-8'><title>Email Verification email</title><link href='css/style.css' type='text/css' rel='stylesheet'/><link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'/> </head><body><div class='wrapper'> <div class='acs-1-1'> </div> <div class='acs-2-1'><div class='content-hi'><h5>You are receiving this email because you havesuccessfully registered in SEXioFIT application.</h5><h5>In order to verify your email,please click the button below:</h5><button class='login-btn-1' onclick='check=1'> verify now</button><h5>You can’t click the button? You can also copy and paste the following link into your browser tocomplete the verification process:</h5><h5 class='login-link'> <a href='google.com' target='_blank'>http://sexiofit-vpserver.com:3000#/users/verify-email/ddcba88227b7da22e869bc0a66af3e7e2c </a></h5><hr class='line-ln'><h5 class='thanks-text'> Thanks <br/>SEXioFIT Team </h5></div></div><div class='acs-3-1'><h1>WE ARE ALSO <br/> AVILABLE ON</h1><div> <img src='img/android-app.png'/></div><div> <img src='img/iphone-app.png'/></div></div><div class='acs-4-1'><div class='acs-4-half'><address> Sexiofit Inc.<br/>225 1 Ave NW, Swift Current, <br/>SK S9H 0N1, Canada  </address> <br/> <br/><div class='f-w'><ul class='social-links'><li> <a href='#'><img src='img/facebook.png'/></a> </li><li> <a href='#'><img src='img/twitter.png'/></a></li><li> <a href='#'><img src='img/youtube.png'/></a></li><li> <a href='#'><img src='img/gplus.png'/></a></li></ul></div></div><div class='acs-4-half'> <div class='f-w ftr-img'> <img src='img/logo-ftr.png'/> <br/> <a href='#'>www.sexiofit.com</a> </div> </div></div></div></body>","text/html" );  

*//* message.setContent(msg, "text/plain");

*/

   message.setContent("<a href='http://localhost:8080/test?email="+to+"'>click here</a>","text/html" );

/*    message.setContent("<a href='/verifyEmail'>click here</div>","text/html" );

*/    } catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}  

   try {

message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

} catch (AddressException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}  

   try {

transport.connect();

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}  

   try {

Transport.send(message);

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}  

   try {

transport.close();

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}   

}

   }

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


Use alternately:

Send mail & verify mail:


package mailsend;


import java.util.Properties;


import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.NoSuchProviderException;

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

public static void main(String[] args){

// Recipient's email ID needs to be mentioned.

String to = email;


logger.info("email sending");

String msg ="Hi "+" "+username;

/* final String addressFrom=from;

*/

Properties props = new Properties();

props.setProperty("mail.transport.protocol", "smtp");

props.setProperty("mail.host", "smtp.gmail.com");

props.put("mail.smtp.auth", "true");

props.put("mail.smtp.port", "465");

props.put("mail.debug", "true");

props.put("mail.smtp.socketFactory.port", "465");

props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");

props.put("mail.smtp.socketFactory.fallback", "false");

/* props.put("mail.smtp.starttls.enable", true);

*/

Session session = Session.getDefaultInstance(props,

new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(from,password);

}

});


//session.setDebug(true);

Transport transport = session.getTransport();

InternetAddress addressFrom = null;

try {

addressFrom = new InternetAddress(from);

} catch (AddressException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


MimeMessage message = new MimeMessage(session);

try {

message.setSender( addressFrom);

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

message.setSubject(subject);

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

message.setSubject("Verification Message");

/* message.setContent(msg+"<head><meta charset='utf-8'><title>Email Verification email</title><link href='css/style.css' type='text/css' rel='stylesheet'/><link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'/> </head><body><div class='wrapper'> <div class='acs-1-1'> </div> <div class='acs-2-1'><div class='content-hi'><h5>You are receiving this email because you havesuccessfully registered in SEXioFIT application.</h5><h5>In order to verify your email,please click the button below:</h5><button class='login-btn-1' onclick='check=1'> verify now</button><h5>You can’t click the button? You can also copy and paste the following link into your browser tocomplete the verification process:</h5><h5 class='login-link'> <a href='google.com' target='_blank'>http://sexiofit-vpserver.com:3000#/users/verify-email/ddcba88227b7da22e869bc0a66af3e7e2c </a></h5><hr class='line-ln'><h5 class='thanks-text'> Thanks <br/>SEXioFIT Team </h5></div></div><div class='acs-3-1'><h1>WE ARE ALSO <br/> AVILABLE ON</h1><div> <img src='img/android-app.png'/></div><div> <img src='img/iphone-app.png'/></div></div><div class='acs-4-1'><div class='acs-4-half'><address> Sexiofit Inc.<br/>225 1 Ave NW, Swift Current, <br/>SK S9H 0N1, Canada </address> <br/> <br/><div class='f-w'><ul class='social-links'><li> <a href='#'><img src='img/facebook.png'/></a> </li><li> <a href='#'><img src='img/twitter.png'/></a></li><li> <a href='#'><img src='img/youtube.png'/></a></li><li> <a href='#'><img src='img/gplus.png'/></a></li></ul></div></div><div class='acs-4-half'> <div class='f-w ftr-img'> <img src='img/logo-ftr.png'/> <br/> <a href='#'>www.sexiofit.com</a> </div> </div></div></div></body>","text/html" );

*//* message.setContent(msg, "text/plain");

*/

message.setContent("<a href='http://localhost:8080/eeee?email="+to+"'>click here</a>","text/html" );

/* message.setContent("<a href='/verifyEmail'>click here</div>","text/html" );

*/ } catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

} catch (AddressException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


try {

transport.connect();

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

Transport.send(message);

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

transport.close();

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return null;

}

@RequestMapping("/verifyEmail")

public @ResponseBody String verifyEmail(@RequestParam String email) throws Exception{

logger.info("hai");

System.out.println("Here");

String url="http://132.148.84.28:2000/users/update";

/* String Authorization='JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.IjU5YjQxOWQxYjNiZWZkMzhkM2JiNzAyMyI.vm5tV2e5NFe2BgZsOexRY3cgl627exqcI3vLp2_BS9c',

*/

//({email: "it.moradi@gmail.com"}, {$set:{verifyEmail: {verificationStatus: true}}})

URL object=new URL(url);

boolean verificationStatus = false;

boolean[] verify={ verificationStatus,true};

JSONObject emailObj = new JSONObject();

emailObj.put("email", email);

emailObj.put("verifyEmail",verify );

HttpURLConnection conn = (HttpURLConnection) object.openConnection();

conn.setConnectTimeout(50000);

conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

conn.setDoInput(true);

conn.setDoOutput(true);

conn.setRequestMethod("POST");

OutputStream os = conn.getOutputStream();

OutputStreamWriter wr = new OutputStreamWriter(os);

wr.write(emailObj.toString());

wr.flush();

os.close();

String json_response = "";

BufferedReader br = null;

if(conn.getResponseCode() == 200)

{

br = new BufferedReader(new

InputStreamReader(conn.getInputStream()));

}

else

{

br = new BufferedReader(new

InputStreamReader(conn.getErrorStream()));

}

String text = "";

while ((text = br.readLine()) != null) {

json_response += text;

}

String response = json_response;

ObjectMapper mapper = new ObjectMapper();

mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

System.out.println("response:"+response);

return null;

}

};



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


package mailsend;

import java.util.*;

import javax.mail.*;

import javax.mail.internet.*;

public class send {

private static String USER_NAME = "kspriyaece1995";  // GMail user name (just the part before "@gmail.com")

private static String PASSWORD = "********"; // GMail password

private static String RECIPIENT = "selvapriya.k@******.com";

public static void main(String[] args) {

    String from = USER_NAME;

    String pass = PASSWORD;

    String[] to = { RECIPIENT }; // list of recipient email addresses

    String subject = "Java send mail example";

    String body = "hi ....,!";

    sendFromGMail(from, pass, to, subject, body);

}

private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {

    Properties props = System.getProperties();

  String host = "smtp.gmail.com";

    props.put("mail.smtp.starttls.enable", "true");

    props.put("mail.smtp.ssl.trust", host);

    props.put("mail.smtp.user", from);

    props.put("mail.smtp.password", pass);

    props.put("mail.smtp.port", "587");

    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);

    MimeMessage message = new MimeMessage(session);

    try {

        message.setFrom(new InternetAddress(from));

        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses

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

            toAddress[i] = new InternetAddress(to[i]);

        }

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

            message.addRecipient(Message.RecipientType.TO, toAddress[i]);

        }

        message.setSubject(subject);

        message.setText(body);

        Transport transport = session.getTransport("smtp");

        transport.connect(host, from, pass);

        transport.sendMessage(message, message.getAllRecipients());

        transport.close();

    }

    catch (AddressException ae) {

        ae.printStackTrace();

    }

    catch (MessagingException me) {

        me.printStackTrace();

    }

    }

   }


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


import java.util.Properties; 

import javax.mail.Message; 

import javax.mail.MessagingException; 

import javax.mail.Session; 

import javax.mail.Transport; 

importjavax.mail.internet.AddressException; 

importjavax.mail.internet.InternetAddress; 

import javax.mail.internet.MimeMessage; 

public class SendMailTLS { 

 public static void main(String[] args) { 

  // To address 

  String to = "to_mail@gmail.com"; 

  // If any CC email ids 

  String cc = "cc@mail.com"; 

  // If any BCC email ids 

  String bcc = "bcc@mail.com"; 

  // Email Subject 

  String subject = "Java Discover"; 

  // Email content 

  String emailText = "Hi All, Welcome to Java Mail API"; 

  // Sending Email using Gmail SMTP 

  sendEmail(to, cc, bcc, subject, emailText); 

 } 

 public static void sendEmail(String to, String cc, String bcc, String subject, String emailText) { 

  // From address (Need Gmail ID) 

  String from = "from_mail@gmail.com"; 

  // Password of from address 

  String password = "from_password"; 

  // Gmail host address 

  String host = "smtp.gmail.com"; 

  Properties props = System.getProperties(); 

  props.put("mail.smtp.host", host); 

  props.put("mail.smtp.socketFactory.port", "465"); 

  props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 

  props.put("mail.smtp.auth", "true"); 

  props.put("mail.smtp.port", "465"); 

  props.put("mail.smtp.user", from); 

  props.put("password", password); 

  Session session = Session.getDefaultInstance(props, null); 

  MimeMessage msg = newMimeMessage(session); 

  try { 

  msg.setFrom(newInternetAddress(from)); 

  // Adding To address 

  msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); 

  // Adding CC email id 

  msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); 

  // Adding BCC email id 

  msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); 

  msg.setSubject(subject); 

  msg.setText(emailText); 

  Transport transport = session.getTransport("smtp"); 

  transport.connect(host, from, password); 

  transport.sendMessage(msg, msg.getAllRecipients()); 

  transport.close(); 

  System.out.println("Email was sent successfully....."); 

  } catch (AddressException e) { 

  e.printStackTrace(); 

  } catch (MessagingException e) { 

  e.printStackTrace(); 

  } 

 } 

}  

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


jars required:

mail-1.4.7.jar:

activation-1.1.1.jar:

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Note : if your Gmail has 2 step verification enable then  your email password will not work, you need to go to your gmail and go to app password in settings

you can go to ->Manage your google account and select  --> security. You could see 2 step verification is ON.

If 2 step verification is ON App password is mandatory, you can see App passwords tab in same page where you see 2 step verifications ON.

click on App Passwords, you will see "Select the app and device you want to generate the app password for."

click on select App drop down , you will see calender, contacts, mail, youtube and others options

click on others then select device dropdown near by.

if you device is available choose that(ipad, windows, mac, etc..) else choose others for custom name.

provide your custom name and click on generate.

Your password must have generated. Use this password for email sending in code where you are asked for password. This app password manages authentications with 2 step verifications.

Thank you,

Selvapriya.k


Post your comments below if you have any doubt   :) :) :)

Comments