Guest User

Untitled

a guest
Jan 4th, 2018
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. package Mailer;
  2.  
  3.  
  4. import org.apache.commons.mail.*;
  5.  
  6. import models.User;
  7.  
  8. import java.util.ArrayList;
  9. import java.util.Properties;
  10.  
  11. import javax.mail.Message;
  12. import javax.mail.MessagingException;
  13. import javax.mail.PasswordAuthentication;
  14. import javax.mail.Session;
  15. import javax.mail.Transport;
  16. import javax.mail.internet.InternetAddress;
  17. import javax.mail.internet.MimeMessage;
  18.  
  19. public class Email{
  20.  
  21. String smtpServer = "smtp.gmail.com";
  22. int port = 587;
  23. final String userid = "hubwateen@gmail.com";//change accordingly
  24. final String password = "Wateen123";//change accordingly
  25. String contentType = "text/html";
  26. String subject = "Test " +
  27. "from the sender";
  28. public void main(ArrayList<Long> userIds) throws Exception {
  29.  
  30. for (Long userId : userIds) {
  31. sendEmail(userId);
  32. }
  33.  
  34. }
  35. public void sendEmail(long id) {
  36.  
  37. String from = "hubwateen@gmail.com";
  38. User user=User.find.byId(id);
  39.  
  40. if(user!=null) {
  41. String to = ""+user.getEmailId();//some invalid address
  42. String bounceAddr = "hubwateen@gmail.com";//change accordingly
  43. String body = "Message";
  44.  
  45. Properties props = new Properties();
  46.  
  47. props.put("mail.smtp.auth", "true");
  48. props.put("mail.smtp.starttls.enable", "true");
  49. props.put("mail.smtp.host", smtpServer);
  50. props.put("mail.smtp.port", "587");
  51. props.put("mail.transport.protocol", "smtp");
  52. props.put("mail.smtp.from", bounceAddr);
  53.  
  54. Session mailSession = Session.getInstance(props,
  55. new javax.mail.Authenticator() {
  56. protected PasswordAuthentication getPasswordAuthentication() {
  57. return new PasswordAuthentication(userid, password);
  58. }
  59. });
  60.  
  61. MimeMessage message = new MimeMessage(mailSession);
  62. try {
  63. message.addFrom(InternetAddress.parse(from));
  64.  
  65. message.setRecipients(Message.RecipientType.TO, to);
  66. message.setSubject(subject);
  67. message.setContent(body, contentType);
  68.  
  69. Transport transport = mailSession.getTransport();
  70.  
  71. transport.close();
  72. System.out.println("Sending ....");
  73. transport.connect(smtpServer, port, userid, password);
  74. transport.sendMessage(message,
  75. message.getRecipients(Message.RecipientType.TO));
  76. System.out.println("Sending done ...");
  77.  
  78. } catch (Exception e) {
  79. System.err.println("Error Sending: ");
  80. e.printStackTrace();
  81. }
  82. }
  83. }// end function main()
  84.  
  85. }
Add Comment
Please, Sign In to add comment