Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Mailer;
- import org.apache.commons.mail.*;
- import models.User;
- import java.util.ArrayList;
- import java.util.Properties;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- public class Email{
- String smtpServer = "smtp.gmail.com";
- int port = 587;
- final String userid = "hubwateen@gmail.com";//change accordingly
- final String password = "Wateen123";//change accordingly
- String contentType = "text/html";
- String subject = "Test " +
- "from the sender";
- public void main(ArrayList<Long> userIds) throws Exception {
- for (Long userId : userIds) {
- sendEmail(userId);
- }
- }
- public void sendEmail(long id) {
- String from = "hubwateen@gmail.com";
- User user=User.find.byId(id);
- if(user!=null) {
- String to = ""+user.getEmailId();//some invalid address
- String bounceAddr = "hubwateen@gmail.com";//change accordingly
- String body = "Message";
- Properties props = new Properties();
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.starttls.enable", "true");
- props.put("mail.smtp.host", smtpServer);
- props.put("mail.smtp.port", "587");
- props.put("mail.transport.protocol", "smtp");
- props.put("mail.smtp.from", bounceAddr);
- Session mailSession = Session.getInstance(props,
- new javax.mail.Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(userid, password);
- }
- });
- MimeMessage message = new MimeMessage(mailSession);
- try {
- message.addFrom(InternetAddress.parse(from));
- message.setRecipients(Message.RecipientType.TO, to);
- message.setSubject(subject);
- message.setContent(body, contentType);
- Transport transport = mailSession.getTransport();
- transport.close();
- System.out.println("Sending ....");
- transport.connect(smtpServer, port, userid, password);
- transport.sendMessage(message,
- message.getRecipients(Message.RecipientType.TO));
- System.out.println("Sending done ...");
- } catch (Exception e) {
- System.err.println("Error Sending: ");
- e.printStackTrace();
- }
- }
- }// end function main()
- }
Add Comment
Please, Sign In to add comment