26 March 2010

Send mail from your gmail account using JavaMail API throught SMTPS

It's not uncommon that the outgoing mail needs to be encrypted using the SMTPS protocol.
It's the case for GMAIL for example.

msgsend.java
--------------------------------------------------------------------
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class msgsend {

    public static void main(String[] argv) throws MessagingException {
        final String SMTP_HOST_NAME = "smtp.gmail.com";
        final int SMTP_HOST_PORT = 465;
        final String SMTP_AUTH_USER = "bangalore.pune.india@gmail.com";
        final String SMTP_AUTH_PWD  = "password";

            Properties props = new Properties();

            props.put("mail.transport.protocol", "smtps");
            props.put("mail.smtps.host", SMTP_HOST_NAME);
            props.put("mail.smtps.auth", "true");
            // props.put("mail.smtps.quitwait", "false");

            Session mailSession = Session.getDefaultInstance(props);
            mailSession.setDebug(true);
            Transport transport = mailSession.getTransport();

            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject("Testing SMTP-SSL");
            message.setContent("This is a test", "text/plain");

            message.addRecipient(Message.RecipientType.TO,
                 new InternetAddress("malay.majithia@gmail.com"));

            transport.connect
              (SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

            transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
            transport.close();
   }
}

You can download JavaMail API from the following link

http://java.sun.com/products/javamail/downloads/index.html

No comments: