Sunday, August 10, 2014

Class to configure email with java mail api

public class SendMail {

final String username = "email@gmail.com";
        final String password = "userpassword";
        final String fromEmail = "email@gmail.com";
        final String subject = "Email text message";
       
        public static void main(String[] args) {

        final String username = "email@gmail.com";
        final String password = "userpassword";

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("email1@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("emaial2@yahoo.in"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");
            message.setContent(message, "text/html; charset=utf-8");
           // Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
    }
   

No comments: