Example usage for javax.mail Transport connect

List of usage examples for javax.mail Transport connect

Introduction

In this page you can find the example usage for javax.mail Transport connect.

Prototype

public void connect(String host, String user, String password) throws MessagingException 

Source Link

Document

Connect to the specified address.

Usage

From source file:nl.nn.adapterframework.senders.MailSender.java

protected void putOnTransport(Message msg) throws SenderException {
    // connect to the transport 
    Transport transport = null;
    try {//from   ww w . ja v  a 2s . c  om
        CredentialFactory cf = new CredentialFactory(getSmtpAuthAlias(), getSmtpUserid(), getSmtpPassword());
        transport = session.getTransport("smtp");
        transport.connect(getSmtpHost(), cf.getUsername(), cf.getPassword());
        if (log.isDebugEnabled()) {
            log.debug("MailSender [" + getName() + "] connected transport to URL [" + transport.getURLName()
                    + "]");
        }
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
    } catch (Exception e) {
        throw new SenderException("MailSender [" + getName() + "] cannot connect send message to smtpHost ["
                + getSmtpHost() + "]", e);
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (MessagingException e1) {
                log.warn("MailSender [" + getName() + "] got exception closing connection", e1);
            }
        }
    }
}

From source file:com.hs.mail.mailet.RemoteDelivery.java

/**
 * We arranged that the recipients are all going to the same mail server. We
 * will now rely on the DNS server to do DNS MX record lookup and try to
 * deliver to the multiple mail servers. If it fails, we should decide that
 * the failure is permanent or temporary.
 * //ww  w  . j  ava 2s.c  o m
 * @param host
 *            the same host of recipients
 * @param recipients
 *            recipients who are all going to the same mail server
 * @param message
 *            Mail object to be delivered
 * @param mimemsg
 *            MIME message representation of the message
 * @return true if the delivery was successful or permanent failure so the
 *         message should be deleted, otherwise false and the message will
 *         be tried to send again later
 */
private boolean deliver(String host, Collection<Recipient> recipients, SmtpMessage message,
        MimeMessage mimemsg) {
    // Prepare javamail recipients
    InternetAddress[] addresses = new InternetAddress[recipients.size()];
    Iterator<Recipient> it = recipients.iterator();
    for (int i = 0; it.hasNext(); i++) {
        Recipient rcpt = it.next();
        addresses[i] = rcpt.toInternetAddress();
    }

    try {
        // Lookup the possible targets
        Iterator<HostAddress> targetServers = null;
        if (null == gateway) {
            targetServers = getSmtpHostAddresses(host);
        } else {
            targetServers = getGatewaySmtpHostAddresses(gateway);
        }
        if (!targetServers.hasNext()) {
            logger.info("No mail server found for: " + host);
            StringBuilder exceptionBuffer = new StringBuilder(128)
                    .append("There are no DNS entries for the hostname ").append(host)
                    .append(".  I cannot determine where to send this message.");
            return failMessage(message, addresses, new MessagingException(exceptionBuffer.toString()), false);
        }

        Properties props = session.getProperties();
        if (message.isNotificationMessage()) {
            props.put("mail.smtp.from", "<>");
        } else {
            props.put("mail.smtp.from", message.getFrom().getMailbox());
        }

        MessagingException lastError = null;
        StringBuilder logBuffer = null;
        HostAddress outgoingMailServer = null;
        while (targetServers.hasNext()) {
            try {
                outgoingMailServer = targetServers.next();
                logBuffer = new StringBuilder(256).append("Attempting to deliver message to host ")
                        .append(outgoingMailServer.getHostName()).append(" at ")
                        .append(outgoingMailServer.getHost()).append(" for addresses ")
                        .append(Arrays.asList(addresses));
                logger.info(logBuffer.toString());
                Transport transport = null;
                try {
                    transport = session.getTransport(outgoingMailServer);
                    try {
                        if (authUser != null) {
                            transport.connect(outgoingMailServer.getHostName(), authUser, authPass);
                        } else {
                            transport.connect();
                        }
                    } catch (MessagingException e) {
                        // Any error on connect should cause the mailet to
                        // attempt to connect to the next SMTP server
                        // associated with this MX record.
                        logger.error(e.getMessage());
                        continue;
                    }
                    transport.sendMessage(mimemsg, addresses);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (MessagingException e) {
                        }
                        transport = null;
                    }
                }
                logBuffer = new StringBuilder(256).append("Successfully sent message to host ")
                        .append(outgoingMailServer.getHostName()).append(" at ")
                        .append(outgoingMailServer.getHost()).append(" for addresses ")
                        .append(Arrays.asList(addresses));
                logger.info(logBuffer.toString());
                recipients.clear();
                return true;
            } catch (SendFailedException sfe) {
                if (sfe.getValidSentAddresses() != null) {
                    Address[] validSent = sfe.getValidSentAddresses();
                    if (validSent.length > 0) {
                        logBuffer = new StringBuilder(256).append("Successfully sent message to host ")
                                .append(outgoingMailServer.getHostName()).append(" at ")
                                .append(outgoingMailServer.getHost()).append(" for addresses ")
                                .append(Arrays.asList(validSent));
                        logger.info(logBuffer.toString());
                        // Remove the addresses to which this message was
                        // sent successfully
                        List<InternetAddress> temp = new ArrayList<InternetAddress>();
                        for (int i = 0; i < addresses.length; i++) {
                            if (!ArrayUtils.contains(validSent, addresses[i])) {
                                if (addresses[i] != null) {
                                    temp.add(addresses[i]);
                                }
                            }
                        }
                        addresses = temp.toArray(new InternetAddress[temp.size()]);
                        removeAll(recipients, validSent);
                    }
                }

                if (sfe instanceof SMTPSendFailedException) {
                    SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                    // If permanent error 5xx, terminate this delivery
                    // attempt by re-throwing the exception
                    if (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599)
                        throw sfe;
                }

                if (!ArrayUtils.isEmpty(sfe.getValidUnsentAddresses())) {
                    // Valid addresses remained, so continue with any other server.
                    if (logger.isDebugEnabled())
                        logger.debug("Send failed, " + sfe.getValidUnsentAddresses().length
                                + " valid recipients(" + Arrays.asList(sfe.getValidUnsentAddresses())
                                + ") remain, continuing with any other servers");
                    lastError = sfe;
                    continue;
                } else {
                    // There are no valid addresses left to send, so re-throw
                    throw sfe;
                }
            } catch (MessagingException me) {
                Exception ne;
                if ((ne = me.getNextException()) != null && ne instanceof IOException) {
                    // It can be some socket or weird I/O related problem.
                    lastError = me;
                    continue;
                }
                throw me;
            }
        } // end while
        if (lastError != null) {
            throw lastError;
        }
    } catch (SendFailedException sfe) {
        boolean deleteMessage = false;

        if (sfe instanceof SMTPSendFailedException) {
            SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
            deleteMessage = (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599);
        } else {
            // Sometimes we'll get a normal SendFailedException with nested
            // SMTPAddressFailedException, so use the latter RetCode
            MessagingException me = sfe;
            Exception ne;
            while ((ne = me.getNextException()) != null && ne instanceof MessagingException) {
                me = (MessagingException) ne;
                if (me instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) me;
                    deleteMessage = (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599);
                }
            }
        }
        if (!ArrayUtils.isEmpty(sfe.getInvalidAddresses())) {
            // Invalid addresses should be considered permanent
            Address[] invalid = sfe.getInvalidAddresses();
            removeAll(recipients, invalid);
            deleteMessage = failMessage(message, invalid, sfe, true);
        }
        if (!ArrayUtils.isEmpty(sfe.getValidUnsentAddresses())) {
            // Vaild-unsent addresses should be considered temporary
            deleteMessage = failMessage(message, sfe.getValidUnsentAddresses(), sfe, false);
        }
        return deleteMessage;
    } catch (MessagingException mex) {
        // Check whether this is a permanent error (like account doesn't
        // exist or mailbox is full or domain is setup wrong)
        // We fail permanently if this was 5xx error.
        return failMessage(message, addresses, mex, ('5' == mex.getMessage().charAt(0)));
    }
    // If we get here, we've exhausted the loop of servers without sending
    // the message or throwing an exception.
    // One case where this might happen is if there is no server we can
    // connect. So this should be considered temporary
    return failMessage(message, addresses, new MessagingException("No mail server(s) available at this time."),
            false);
}

From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java

private void sendMessage(String subject, String message, InternetAddress from, InternetAddress[] recipients,
        InternetAddress[] cclist, File attachedFile) throws MessagingException, IOException {
    log.info("try to send: " + printEmail(subject, message, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
    log.info("host: " + host + ", useSMTPS: " + useSmtps);
    Properties props = new Properties();
    String protocol = "smtp";
    if (useSmtps) // need smtps to test with gmail
    {//from   w  ww  .j av a  2  s  .  com
        props.put("mail.smtps.auth", "true");
        protocol = "smtps";
    }
    Session session = Session.getDefaultInstance(props, null);
    Transport t = session.getTransport(protocol);

    try {
        MimeMessage msg = new MimeMessage(session);
        if (this.replyTos != null)
            msg.setReplyTo(replyTos);
        msg.setFrom(from);
        msg.setSubject(subject);

        if (attachedFile != null) {
            setFileAsAttachment(msg, message, attachedFile);
        } else {
            msg.setContent(message, "text/plain");
        }

        msg.addRecipients(Message.RecipientType.TO, recipients);
        if (cclist != null)
            msg.addRecipients(Message.RecipientType.CC, cclist);

        t.connect(host, username, password);
        t.sendMessage(msg, msg.getAllRecipients());
    } finally {
        t.close();
    }
    log.info("sent: " + printEmailHeader(subject, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
}

From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java

/**
 * Send an mail containing the error message back to the
 * user which sent the given message.//from   w w w.  jav  a  2 s  .  c om
 *
 * @param m The message which produced an error while handling it.
 * @param error The error string.
 */
private void sendErrorMessage(Message m, String error) throws Exception {
    /* get the SMTP mail server */
    SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer();
    if (smtpMailServer == null) {
        log.warn("Failed to send error message as no SMTP server is configured");
        return;
    }

    /* get system properties */
    Properties props = System.getProperties();

    /* Setup mail server */
    props.put("mail.smtp.host", smtpMailServer.getHostname());

    /* get a session */
    Session session = Session.getDefaultInstance(props, null);
    /* create the message */
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom()));
    String senderEmail = getEmailAddressFromMessage(m);
    if (senderEmail == "") {
        throw new Exception("Unknown sender of email.");
    }
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail));
    message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")");
    message.setText("An error occurred while handling your message:\n\n  " + error
            + "\n\nPlease contact the administrator to solve the problem.\n");

    /* send the message */
    Transport tr = session.getTransport("smtp");
    if (StringUtils.isBlank(smtpMailServer.getSmtpPort())) {
        tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword());
    } else {
        int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort());
        tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(),
                smtpMailServer.getPassword());
    }
    message.saveChanges();
    tr.sendMessage(message, message.getAllRecipients());
    tr.close();
}

From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java

/**
 * Sends message to mailserver, waiting for delivery if using synchronous
 * mode.//  w w  w.j a  v  a2s. com
 *
 * @param message
 *            Message previously prepared by prepareMessage()
 * @throws MessagingException
 *             when problems sending the mail arise
 * @throws IOException
 *             TODO can not see how
 * @throws InterruptedException
 *             when interrupted while waiting for delivery in synchronous
 *             modus
 */
public void execute(Message message) throws MessagingException, IOException, InterruptedException {

    Transport tr = null;
    try {
        tr = session.getTransport(getProtocol());
        SynchronousTransportListener listener = null;

        if (synchronousMode) {
            listener = new SynchronousTransportListener();
            tr.addTransportListener(listener);
        }

        if (useAuthentication) {
            tr.connect(smtpServer, username, password);
        } else {
            tr.connect();
        }

        tr.sendMessage(message, message.getAllRecipients());

        if (listener != null /*synchronousMode==true*/) {
            listener.attend(); // listener cannot be null here
        }
    } finally {
        if (tr != null) {
            try {
                tr.close();
            } catch (Exception e) {
                // NOOP
            }
        }
        logger.debug("transport closed");
    }

    logger.debug("message sent");
    return;
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "")
@APIParam(params = { "url", "function(data)" })
public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings)
        throws AddressException, MessagingException {

    if (emailSettings == null) {
        return;//  w  w w  .  j  ava  2 s  . c om
    }

    // final String host = "smtp.gmail.com";
    // final String address = "@gmail.com";
    // final String pass = "";

    Multipart multiPart;
    String finalString = "";

    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", emailSettings.ttl);
    props.put("mail.smtp.host", emailSettings.host);
    props.put("mail.smtp.user", emailSettings.user);
    props.put("mail.smtp.password", emailSettings.password);
    props.put("mail.smtp.port", emailSettings.port);
    props.put("mail.smtp.auth", emailSettings.auth);

    Log.i("Check", "done pops");
    final Session session = Session.getDefaultInstance(props, null);
    DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
    final MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setDataHandler(handler);
    Log.i("Check", "done sessions");

    multiPart = new MimeMultipart();

    InternetAddress toAddress;
    toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Log.i("Check", "added recipient");
    message.setSubject(subject);
    message.setContent(multiPart);
    message.setText(text);

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                MLog.i("check", "transport");
                Transport transport = session.getTransport("smtp");
                MLog.i("check", "connecting");
                transport.connect(emailSettings.host, emailSettings.user, emailSettings.password);
                MLog.i("check", "wana send");
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();

                MLog.i("check", "sent");

            } catch (AddressException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }

        }
    });
    t.start();

}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

protected void sendMessageAndLog(InternetAddress from, InternetAddress[] to, String subject,
        Map<RecipientType, InternetAddress[]> headerTo, long start, MimeMessage msg, Session session)
        throws MessagingException {
    long preSend = 0;
    if (M_log.isDebugEnabled())
        preSend = System.currentTimeMillis();

    if (allowTransport) {
        msg.saveChanges();//from www  .  ja  v a  2 s  .c o  m

        Transport transport = session.getTransport(protocol);

        if (m_smtpUser != null && m_smtpPassword != null)
            transport.connect(m_smtp, m_smtpUser, m_smtpPassword);
        else
            transport.connect();

        transport.sendMessage(msg, to);

        transport.close();
    }

    long end = 0;
    if (M_log.isDebugEnabled())
        end = System.currentTimeMillis();

    if (M_log.isInfoEnabled()) {
        StringBuilder buf = new StringBuilder();
        buf.append("Email.sendMail: from: ");
        buf.append(from);
        buf.append(" subject: ");
        buf.append(subject);
        buf.append(" to:");
        for (int i = 0; i < to.length; i++) {
            buf.append(" ");
            buf.append(to[i]);
        }
        if (headerTo != null) {
            if (headerTo.containsKey(RecipientType.TO)) {
                buf.append(" headerTo{to}:");
                InternetAddress[] headerToTo = headerTo.get(RecipientType.TO);
                for (int i = 0; i < headerToTo.length; i++) {
                    buf.append(" ");
                    buf.append(headerToTo[i]);
                }
            }
            if (headerTo.containsKey(RecipientType.CC)) {
                buf.append(" headerTo{cc}:");
                InternetAddress[] headerToCc = headerTo.get(RecipientType.CC);
                for (int i = 0; i < headerToCc.length; i++) {
                    buf.append(" ");
                    buf.append(headerToCc[i]);
                }
            }
            if (headerTo.containsKey(RecipientType.BCC)) {
                buf.append(" headerTo{bcc}:");
                InternetAddress[] headerToBcc = headerTo.get(RecipientType.BCC);
                for (int i = 0; i < headerToBcc.length; i++) {
                    buf.append(" ");
                    buf.append(headerToBcc[i]);
                }
            }
        }
        try {
            if (msg.getContent() instanceof Multipart) {
                Multipart parts = (Multipart) msg.getContent();
                buf.append(" with ").append(parts.getCount() - 1).append(" attachments");
            }
        } catch (IOException ioe) {
        }

        if (M_log.isDebugEnabled()) {
            buf.append(" time: ");
            buf.append("" + (end - start));
            buf.append(" in send: ");
            buf.append("" + (end - preSend));
        }

        M_log.info(buf.toString());
    }
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * {@inheritDoc}/* ww w  . ja  v a2 s . c  o m*/
 */
public void sendToUsers(Collection<User> users, Collection<String> headers, String message) {
    if (headers == null) {
        M_log.warn("sendToUsers: null headers");
        return;
    }

    if (m_testMode) {
        M_log.info("sendToUsers: users: " + usersToStr(users) + " headers: " + listToStr(headers)
                + " message:\n" + message);
        return;
    }

    if (m_smtp == null) {
        M_log.warn("sendToUsers: smtp not set");
        return;
    }

    if (users == null) {
        M_log.warn("sendToUsers: null users");
        return;
    }

    if (message == null) {
        M_log.warn("sendToUsers: null message");
        return;
    }

    // form the list of to: addresses from the users users collection
    ArrayList<InternetAddress> addresses = new ArrayList<InternetAddress>();
    for (User user : users) {
        String email = user.getEmail();
        if ((email != null) && (email.length() > 0)) {
            try {
                addresses.add(new InternetAddress(email));
            } catch (AddressException e) {
                if (M_log.isDebugEnabled())
                    M_log.debug("sendToUsers: " + e);
            }
        }
    }

    // if we have none
    if (addresses.isEmpty())
        return;

    // how many separate messages do we need to send to keep each one at or under m_maxRecipients?
    int numMessageSets = ((addresses.size() - 1) / m_maxRecipients) + 1;

    // make an array for each and store them all in the collection
    ArrayList<Address[]> messageSets = new ArrayList<Address[]>();
    int posInAddresses = 0;
    for (int i = 0; i < numMessageSets; i++) {
        // all but the last one are max size
        int thisSize = m_maxRecipients;
        if (i == numMessageSets - 1) {
            thisSize = addresses.size() - ((numMessageSets - 1) * m_maxRecipients);
        }

        // size an array
        Address[] toAddresses = new Address[thisSize];
        messageSets.add(toAddresses);

        // fill the array
        int posInToAddresses = 0;
        while (posInToAddresses < thisSize) {
            toAddresses[posInToAddresses] = (Address) addresses.get(posInAddresses);
            posInToAddresses++;
            posInAddresses++;
        }
    }

    // get a session for our smtp setup, include host, port, reverse-path, and set partial delivery
    Properties props = createMailSessionProperties();

    Session session = Session.getInstance(props);

    // form our Message
    MimeMessage msg = new MyMessage(session, headers, message);

    // fix From and ReplyTo if necessary
    checkFrom(msg);

    // transport the message
    long time1 = 0;
    long time2 = 0;
    long time3 = 0;
    long time4 = 0;
    long time5 = 0;
    long time6 = 0;
    long timeExtraConnect = 0;
    long timeExtraClose = 0;
    long timeTmp = 0;
    int numConnects = 1;
    try {
        if (M_log.isDebugEnabled())
            time1 = System.currentTimeMillis();
        Transport transport = session.getTransport(protocol);

        if (M_log.isDebugEnabled())
            time2 = System.currentTimeMillis();
        msg.saveChanges();

        if (M_log.isDebugEnabled())
            time3 = System.currentTimeMillis();
        if (m_smtpUser != null && m_smtpPassword != null)
            transport.connect(m_smtp, m_smtpUser, m_smtpPassword);
        else
            transport.connect();

        if (M_log.isDebugEnabled())
            time4 = System.currentTimeMillis();

        // loop the send for each message set
        for (Iterator<Address[]> i = messageSets.iterator(); i.hasNext();) {
            Address[] toAddresses = i.next();

            try {
                transport.sendMessage(msg, toAddresses);

                // if we need to use the connection for just one send, and we have more, close and re-open
                if ((m_oneMessagePerConnection) && (i.hasNext())) {
                    if (M_log.isDebugEnabled())
                        timeTmp = System.currentTimeMillis();
                    transport.close();
                    if (M_log.isDebugEnabled())
                        timeExtraClose += (System.currentTimeMillis() - timeTmp);

                    if (M_log.isDebugEnabled())
                        timeTmp = System.currentTimeMillis();
                    transport.connect();
                    if (M_log.isDebugEnabled()) {
                        timeExtraConnect += (System.currentTimeMillis() - timeTmp);
                        numConnects++;
                    }
                }
            } catch (SendFailedException e) {
                if (M_log.isDebugEnabled())
                    M_log.debug("sendToUsers: " + e);
            } catch (MessagingException e) {
                M_log.warn("sendToUsers: " + e);
            }
        }

        if (M_log.isDebugEnabled())
            time5 = System.currentTimeMillis();
        transport.close();

        if (M_log.isDebugEnabled())
            time6 = System.currentTimeMillis();
    } catch (MessagingException e) {
        M_log.warn("sendToUsers:" + e);
    }

    // log
    if (M_log.isInfoEnabled()) {
        StringBuilder buf = new StringBuilder();
        buf.append("sendToUsers: headers[");
        for (String header : headers) {
            buf.append(" ");
            buf.append(cleanUp(header));
        }
        buf.append("]");
        for (Address[] toAddresses : messageSets) {
            buf.append(" to[ ");
            for (int a = 0; a < toAddresses.length; a++) {
                buf.append(" ");
                buf.append(toAddresses[a]);
            }
            buf.append("]");
        }

        if (M_log.isDebugEnabled()) {
            buf.append(" times[ ");
            buf.append(" getransport:" + (time2 - time1) + " savechanges:" + (time3 - time2) + " connect(#"
                    + numConnects + "):" + ((time4 - time3) + timeExtraConnect) + " send:"
                    + (((time5 - time4) - timeExtraConnect) - timeExtraClose) + " close:"
                    + ((time6 - time5) + timeExtraClose) + " total: " + (time6 - time1) + " ]");
        }

        M_log.info(buf.toString());
    }
}

From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java

private void createAndSendMessage(Transport transport, String subject, String text, String nameFrom,
        String emailFrom, Emails emails, String ip) { // Assuming you are sending email from localhost
    String host = ConfigManager.getInstance().getSmtpMailhost();
    String port = ConfigManager.getInstance().getSmtpMailport();
    String password = ConfigManager.getInstance().getSmtpMailpassword();
    String auth = ConfigManager.getInstance().getSmtpMailauth();
    String sender = ConfigManager.getInstance().getSmtpMailuser();

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.starttls.enable", "true");
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.smtp.user", sender);
    properties.setProperty("mail.smtp.password", password);
    properties.setProperty("mail.smtp.auth", auth);
    properties.setProperty("mail.smtp.port", port);

    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // Create a default MimeMessage object.
    MimeMessage message = new MimeMessage(session);

    // Set From: header field of the header.
    if (!StringUtils.isBlank(sender)) {
        try {/*from   w  w  w .  j  a  va2 s .  c  o m*/
            message.setFrom(new InternetAddress(sender));

        } catch (AddressException ex) {
            logger.log(Level.SEVERE, "Sender address is not a valid mail address" + sender, ex);
        } catch (MessagingException ex) {
            logger.log(Level.SEVERE, "Can't create message for Sender: " + sender + " due to", ex);
        }

    }

    List<Address> addresses = new ArrayList<Address>();

    String receivers = emails.getReceivers();
    receivers = StringUtils.trim(receivers);

    for (String receiver : receivers.split(";")) {
        if (!StringUtils.isBlank(receiver)) {
            try {
                addresses.add(new InternetAddress(receiver));
            } catch (AddressException ex) {
                logger.log(Level.SEVERE, "Receiver address is not a valid mail address" + receiver, ex);
            } catch (MessagingException ex) {
                logger.log(Level.SEVERE, "Can't create message for Receiver: " + receiver + " due to", ex);
            }
        }
    }
    Address[] add = new Address[addresses.size()];
    addresses.toArray(add);
    try {
        message.addRecipients(Message.RecipientType.TO, add);

        // Set Subject: header field
        message.setSubject("[Pundit Contact Form]: " + subject);

        // Now set the actual message
        message.setText("Subject: " + subject + " \n" + "From: " + nameFrom + " (email: " + emailFrom + ") \n"
                + "Date: " + new Date() + "\n" + "IP: " + ip + "\n" + "Text: \n" + text);

    } catch (MessagingException ex) {
        logger.log(Level.SEVERE, "Can't create message for Recipient: " + add + " due to", ex);
    }
    // Send message

    try {
        logger.log(Level.INFO, "Trying to send message to receivers: {0}",
                Arrays.toString(message.getAllRecipients()));
        transport = session.getTransport("smtp");
        transport.connect(host, sender, password);
        transport.sendMessage(message, message.getAllRecipients());
        logger.log(Level.INFO, "Sent messages to all receivers {0}",
                Arrays.toString(message.getAllRecipients()));
    } catch (NoSuchProviderException nspe) {
        logger.log(Level.SEVERE, "Cannot find smtp provider", nspe);
    } catch (MessagingException me) {
        logger.log(Level.SEVERE, "Cannot set transport layer ", me);
    } finally {
        try {

            transport.close();
        } catch (MessagingException ex) {

        } catch (NullPointerException ne) {
        }

    }

}

From source file:library.Form_Library.java

License:asdf

public void sendFromGMail(String from, String pass, String to, String subject, String body) {
    this.taBaoCao.append("Sent to " + to + " successfully.\n");
    Properties props = System.getProperties();
    String host = "smtp.gmail.com";
    props.put("mail.smtp.starttls.enable", "true");
    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");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {//w  w  w .j  a  v a2s  .co m
        message.setFrom(new InternetAddress(from));
        InternetAddress toAddress = new InternetAddress();

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

        //            for( int i = 0; i < toAddress.length; i++) {
        message.addRecipient(Message.RecipientType.TO, toAddress);
        //            }

        message.setSubject(subject);
        message.setText(body);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);

        transport.sendMessage(message, message.getAllRecipients());

        System.out.print("Successfully Sent" + "\n");
        transport.close();
    } catch (AddressException ae) {
        ae.printStackTrace();
    } catch (MessagingException me) {
        me.printStackTrace();
    }
}