Java Mail Over SSL(Gmail As Example)

This is a sample program which can send a mail using gmail server as smtp host.

import java.security.Security;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This sends mail to Intended receipients using Gmail SMTP Server and Account
 *
 * @author Ashwin
 *
 */
public class MailSender {

    private static final transient Log logger = LogFactory
    .getLog(MailSender.class);

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String emailMsgTxt = "Test Message Contents";
    private static final String emailSubjectTxt = "A test from gmail";
    private static final String emailFromAddress = "filelistener.fujitsu@test";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String[] sendTo = { "ashwin.rayaprolu@idhasoft.com",
            "ashwin.rayaprolu@gmail.com" };

    public static void main(String args[]) throws Exception {

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        String[] filenames = { "c:\\create_tables_oracle.sql" };

        new MailSender().sendSSLMessage(Arrays.asList(sendTo), emailSubjectTxt, emailMsgTxt,
                emailFromAddress, filenames);
        System.out.println("Sucessfully Sent mail to All Users");
    }

    /**
     * @param recipients
     * @param subject
     * @param messageContent
     * @param from
     * @param attachments
     * @throws Exception
     */
    public static void sendMail(List recipients, String subject,
            String messageContent, String from, String[] attachments)
            throws Exception {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        String[] filenames = { "c:\\create_tables_oracle.sql" };

        new MailSender().sendSSLMessage(recipients, subject, messageContent,
                from, filenames);
        System.out.println("Sucessfully Sent mail to All Users");
    }

    /**
     * @param attachments
     * @param multipart
     * @throws MessagingException
     * @throws AddressException
     */
    protected void addAtachments(String[] attachments, Multipart multipart)
            throws MessagingException, AddressException {
        for (int i = 0; i <= attachments.length - 1; i++) {
            String filename = attachments[i];
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();

            // use a JAF FileDataSource as it does MIME type detection
            DataSource source = new FileDataSource(filename);
            attachmentBodyPart.setDataHandler(new DataHandler(source));

            // assume that the filename you want to send is the same as the
            // actual file name - could alter this to remove the file path
            attachmentBodyPart.setFileName(filename);

            // add the attachment
            multipart.addBodyPart(attachmentBodyPart);
        }
    }

    /**
     * @param recipients
     * @param subject
     * @param messageContent
     * @param from
     * @throws MessagingException
     */
    public void sendSSLMessage(List recipients, String subject,
            String messageContent, String from, String[] attachments)
            throws MessagingException {
        boolean debug = false;

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(
                                "username", "password");
                    }
                });

        session.setDebug(debug);

        Message message = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(from);
        message.setFrom(addressFrom);

        for (Iterator it = recipients.iterator(); it.hasNext();) {
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress((String) it.next()));
        }

        // Setting the Subject and Content Type
        message.setSubject(subject);

        // Create a message part to represent the body text
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(messageContent, "text/html");

        // use a MimeMultipart as we need to handle the file attachments
        Multipart multipart = new MimeMultipart();

        // add the message body to the mime message
        multipart.addBodyPart(messageBodyPart);

        // add any file attachments to the message
        addAtachments(attachments, multipart);

        // Put all message parts in the message
        message.setContent(multipart);

        Transport.send(message);

        logger.info("Sent Mail ");
    }
}

Kindly comment incase of any queries
Advertisements

14 thoughts on “Java Mail Over SSL(Gmail As Example)

    • the smtp with autentification is born to verifiy the sender and it is required ssl/tls connection. you cannot modify the sender.

  1. I got the following output

    DEBUG: JavaMail version 1.4.1
    DEBUG: not loading file: C:\Program Files\Java\jre6\lib\javamail.providers
    DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre6\lib\javamail.providers (The system cannot find the file specified)
    DEBUG: !anyLoaded
    DEBUG: not loading resource: /META-INF/javamail.providers
    DEBUG: not loading resource: /META-INF/javamail.default.providers
    DEBUG: failed to load any providers, using defaults
    DEBUG: Tables of loaded providers
    DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc.,1.4.1], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc.,1.4.1], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc.,1.4.1], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc.,1.4.1], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc.,1.4.1], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc.,1.4.1]}
    DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc.,1.4.1], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc.,1.4.1], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc.,1.4.1], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc.,1.4.1], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc.,1.4.1], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc.,1.4.1]}
    DEBUG: not loading resource: /META-INF/javamail.default.address.map
    DEBUG: !anyLoaded
    DEBUG: not loading resource: /META-INF/javamail.address.map
    DEBUG: not loading file: C:\Program Files\Java\jre6\lib\javamail.address.map
    DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre6\lib\javamail.address.map (The system cannot find the file specified)
    DEBUG: failed to load address map, using defaults
    Exception in thread “main” javax.mail.NoSuchProviderException: smtp
    at javax.mail.Session.getService(Session.java:780)
    at javax.mail.Session.getTransport(Session.java:718)
    at javax.mail.Session.getTransport(Session.java:661)
    at javax.mail.Session.getTransport(Session.java:641)
    at javax.mail.Session.getTransport(Session.java:696)
    at javax.mail.Transport.send0(Transport.java:186)
    at javax.mail.Transport.send(Transport.java:118)
    at MailSender.sendSSLMessage(MailSender.java:162)
    at MailSender.main(MailSender.java:52)

  2. DEBUG: not loading system providers in /lib
    DEBUG: not loading optional custom providers file: /META-INF/javamail.providers
    DEBUG: successfully loaded default providers

    DEBUG: Tables of loaded providers
    DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.
    SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,
    Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsyste
    ms, Inc]}
    DEBUG: Providers Listed By Protocol: {imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc],
    pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,s
    mtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
    DEBUG: not loading optional address map file: /META-INF/javamail.address.map

  3. Overall, Business Link seems very consumer friendly, with added information about Services not only products being
    covered in the act, and giving the consumer advice on what to do in the
    situation and what should be covered by the retailer in terms to
    your product going wrong. Opioids can offer short, intermediate and longer lasting
    analgesia, dependant on the particular properties from the medication (( An opioid is really a chemical
    that actually works by binding to opioid receptors, that happen to be found
    principally in the nerves inside the body and also the gastrointestinal tract.
    Keep your eyes and ears open for almost any new site polices
    regarding this issue.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s