Advertisement
Guest User

Untitled

a guest
Mar 9th, 2017
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. public class GMailSender extends javax.mail.Authenticator {
  2. private String mailhost = "smtp.gmail.com";
  3. private String user;
  4. private String password;
  5. private Session session;
  6.  
  7. static {
  8. Security.addProvider(new JSSEProvider());
  9. }
  10.  
  11. public GMailSender(String user, String password) {
  12. this.user = user;
  13. this.password = password;
  14.  
  15. Properties props = new Properties();
  16. props.setProperty("mail.transport.protocol", "smtp");
  17. props.setProperty("mail.host", mailhost);
  18. props.put("mail.smtp.auth", "true");
  19. props.put("mail.smtp.port", "465");
  20. props.put("mail.smtp.socketFactory.port", "465");
  21. props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  22. props.put("mail.smtp.socketFactory.fallback", "false");
  23. props.setProperty("mail.smtp.quitwait", "false");
  24.  
  25. session = Session.getDefaultInstance(props, this);
  26. }
  27.  
  28. protected PasswordAuthentication getPasswordAuthentication() {
  29. return new PasswordAuthentication(user, password);
  30. }
  31.  
  32. public synchronized void sendMail(String subject, String body,
  33. String sender, String recipients) throws Exception {
  34. MimeMessage message = new MimeMessage(session);
  35. DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
  36. message.setSender(new InternetAddress(sender));
  37. message.setSubject(subject);
  38. message.setDataHandler(handler);
  39.  
  40. if (recipients.indexOf(',') > 0)
  41. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
  42. else
  43. message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
  44.  
  45. Transport.send(message);
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement