Tuesday, May 22, 2012

Send mail with smtps attached to Transport

        String host = "smtp.gmail.com";
        String from = "xxxxxx@gmail.com";
        String pass = "xxxxx";
        System.out.println("Water2");
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

            emailId = "mathew";

        String[] to = {emailId+"@cxxxx.com"};/*, emailId}; */ // added this line

        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i=0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i=0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }
        message.setSubject("Result of running "+testName);
//        message.setText("Check out the attached test report");
//        http://www.jguru.com/faq/view.jsp?EID=30251

        /* For Body Part */

        MimeBodyPart messageBodyPart =
          new MimeBodyPart();

        messageBodyPart.setText("Check out the attached test report");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        String fileAttachment = System.getProperty("user.dir")+"/test-output/emailable-report.html";
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileAttachment);
        messageBodyPart.setDataHandler( new DataHandler(source));
        messageBodyPart.setFileName("Test-Report");
        multipart.addBodyPart(messageBodyPart);
        // Put parts in message
        message.setContent(multipart);

        /*------*/

        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

No comments:

Post a Comment