Advertisement
Guest User

Untitled

a guest
Jun 15th, 2015
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. private String userpass;
  2.     private String from;
  3.    
  4.     //attachments not required
  5.     private boolean sendMail(String to, String user, String pass, String subject, String p_message){
  6.         from = user;
  7.         userpass = pass;
  8.  
  9.         String host = "localhost";
  10.         Properties props = new Properties();
  11.         props.setProperty("mail.smtp.ssl.enable", "true");
  12.         props.put("mail.smtp.starttls.enable", "true");
  13.         props.put("mail.smtp.auth", "true");
  14.         props.put("mail.smtp.host", "smtp.gmail.com");
  15.         props.put("mail.smtp.port", "587");
  16.        
  17.        
  18.         props.put("mail.imap.ssl.enable", "true"); // required for Gmail
  19.         props.put("mail.imap.sasl.enable", "true");
  20.         props.put("mail.imap.sasl.mechanisms", "XOAUTH2");
  21.         props.put("mail.imap.auth.login.disable", "true");
  22.         props.put("mail.imap.auth.plain.disable", "true");
  23.  
  24.         Session session = Session.getInstance(props,
  25.           new javax.mail.Authenticator() {
  26.             protected PasswordAuthentication getPasswordAuthentication() {
  27.                 return new PasswordAuthentication(from, userpass);
  28.             }
  29.           });
  30.         try{
  31.             Store store = session.getStore("imap");
  32.             store.connect("imap.gmail.com", from, userpass);
  33.         }
  34.         catch (Exception e){
  35.             e.printStackTrace();
  36.         }
  37.         try {
  38.  
  39.             Message message = new MimeMessage(session);
  40.             message.setFrom(new InternetAddress(from));
  41.             message.setRecipients(Message.RecipientType.TO,
  42.                 InternetAddress.parse(to));
  43.             message.setSubject(subject);
  44.             message.setText(p_message);
  45.  
  46.             Transport.send(message);
  47.  
  48.             System.out.println("Sent to "+to);
  49.             return true;
  50.         }
  51.         catch (javax.mail.AuthenticationFailedException auth_e){
  52.             auth_e.printStackTrace();
  53.             System.out.println("Invalid username or password");
  54.             return false;
  55.         }
  56.         catch (MessagingException e) {
  57.             e.printStackTrace();
  58.             return false;
  59.         }
  60.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement