Search This Blog

Wednesday, 3 September 2014

Sending Email using Java

Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com"); // for gmail use smtp.gmail.com
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {

                @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(getUserName()/*gmail username in Strings */, getPassword()/*gmail password in Strings*/ );
                                               
            }
        });
             System.out.println("Pasword::"+getPassword());
        mailSession.setDebug(true); // Enable the debug mode

        Message msg = new MimeMessage( mailSession );

        //--[ Set the FROM, TO, DATE and SUBJECT fields
        msg.setFrom( new InternetAddress( getUserName()/*"your gmail user name"*/ ) );
        msg.setRecipients( Message.RecipientType.TO,InternetAddress.parse(getTo()/*any which person your sendibg that person mail id in Strings*/) );
        msg.setSentDate( new Date());
        msg.setSubject( getSubject()/*Subject of your mail*/ );

        //--[ Create the body of the mail
        msg.setText( getMessage()/*your message*/ );
//--[ Ask the Transport class to send our mail message
        Transport.send( msg );//sending the message

No comments:

Post a Comment