Guest User

Untitled

a guest
Dec 14th, 2017
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. public class MailServlet extends HttpServlet
  2. {
  3. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
  4. ServletException, IOException
  5. {
  6. try {
  7. sendMail("smtpHost", "user", "pass", "from", "to", "subject","text");
  8. } catch (Exception e) {
  9. }
  10. }
  11.  
  12. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  13. throws ServletException, IOException
  14. {}
  15.  
  16. public static void sendMail(String smtpHost,String username,String password,String senderAddress,String recipientsAddress,String subject,String text ) throws Exception
  17. {
  18. MailAuthenticator auth = new MailAuthenticator(username, password);
  19. Properties properties = new Properties();
  20. properties.put("mail.smtp.host", smtpHost);
  21. properties.put("mail.smtp.auth", "true");
  22. properties.put("mail.smtp.socketFactory.port", "465");
  23. properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  24. Session session = Session.getDefaultInstance(properties, auth);
  25. Message msg = new MimeMessage(session);
  26. msg.setFrom(new InternetAddress(senderAddress));
  27. msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientsAddress, false));
  28. msg.setSubject(subject);
  29. msg.setText(text);
  30. msg.setHeader("Recall", "Recall");
  31. msg.setSentDate(new Date( ));
  32. Transport.send(msg);
  33. }
  34. }
  35.  
  36. class MailAuthenticator extends Authenticator
  37. {
  38. private final String user;
  39. private final String password;
  40. public MailAuthenticator(String user, String password)
  41. {
  42. this.user = user;
  43. this.password = password;
  44. }
  45. protected PasswordAuthentication getPasswordAuthentication()
  46. {
  47. return new PasswordAuthentication(this.user, this.password);
  48. }
  49. }
Add Comment
Please, Sign In to add comment