Example usage for javax.mail Transport close

List of usage examples for javax.mail Transport close

Introduction

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

Prototype

public synchronized void close() throws MessagingException 

Source Link

Document

Close this service and terminate its connection.

Usage

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);/*from  ww w  . jav  a 2s .c  om*/
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

    // add the Multipart to the message
    message.setContent(mp);

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

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  .j ava2 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 ava 2 s  .  c o m*/
 *
 * @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: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.
 * /*from  w w w .ja  va2  s  .co  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:com.panet.imeta.trans.steps.mail.Mail.java

public void sendMail(Object[] r, String server, String port, String senderAddress, String senderName,
        String destination, String destinationCc, String destinationBCc, String contactPerson,
        String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject,
        String comment, String replyToAddresses) throws Exception {

    // Send an e-mail...
    // create some properties and get the default Session

    String protocol = "smtp";
    if (meta.isUsingAuthentication()) {
        if (meta.getSecureConnectionType().equals("TLS")) {
            // Allow TLS authentication
            data.props.put("mail.smtp.starttls.enable", "true");
        } else {/*ww  w .j a  v  a  2  s. c o  m*/
            protocol = "smtps";
            // required to get rid of a SSL exception :
            //  nested exception is:
            //  javax.net.ssl.SSLException: Unsupported record version Unknown
            data.props.put("mail.smtps.quitwait", "false");
        }
    }
    data.props.put("mail." + protocol + ".host", server);
    if (!Const.isEmpty(port))
        data.props.put("mail." + protocol + ".port", port);
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        data.props.put("mail.debug", "true");

    if (meta.isUsingAuthentication())
        data.props.put("mail." + protocol + ".auth", "true");

    Session session = Session.getInstance(data.props);
    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set message priority
    if (meta.isUsePriority()) {
        String priority_int = "1";
        if (meta.getPriority().equals("low"))
            priority_int = "3";
        if (meta.getPriority().equals("normal"))
            priority_int = "2";

        msg.setHeader("X-Priority", priority_int); //(String)int between 1= high and 3 = low.
        msg.setHeader("Importance", meta.getImportance());
        //seems to be needed for MS Outlook.
        //where it returns a string of high /normal /low.
    }

    // set Email sender
    String email_address = senderAddress;
    if (!Const.isEmpty(email_address)) {
        // get sender name
        if (!Const.isEmpty(senderName))
            email_address = senderName + '<' + email_address + '>';
        msg.setFrom(new InternetAddress(email_address));
    } else {
        throw new MessagingException(Messages.getString("Mail.Error.ReplyEmailNotFilled"));
    }

    // Set reply to 
    if (!Const.isEmpty(replyToAddresses)) {
        // get replay to
        // Split the mail-address: space separated
        String[] reply_Address_List = replyToAddresses.split(" ");
        InternetAddress[] address = new InternetAddress[reply_Address_List.length];

        for (int i = 0; i < reply_Address_List.length; i++)
            address[i] = new InternetAddress(reply_Address_List[i]);

        // To add the real reply-to 
        msg.setReplyTo(address);
    }

    // Split the mail-address: space separated
    String destinations[] = destination.split(" ");
    InternetAddress[] address = new InternetAddress[destinations.length];
    for (int i = 0; i < destinations.length; i++)
        address[i] = new InternetAddress(destinations[i]);

    msg.setRecipients(Message.RecipientType.TO, address);

    String realdestinationCc = destinationCc;
    if (!Const.isEmpty(realdestinationCc)) {
        // Split the mail-address Cc: space separated
        String destinationsCc[] = realdestinationCc.split(" ");
        InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
        for (int i = 0; i < destinationsCc.length; i++)
            addressCc[i] = new InternetAddress(destinationsCc[i]);

        msg.setRecipients(Message.RecipientType.CC, addressCc);
    }

    String realdestinationBCc = destinationBCc;
    if (!Const.isEmpty(realdestinationBCc)) {
        // Split the mail-address BCc: space separated
        String destinationsBCc[] = realdestinationBCc.split(" ");
        InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
        for (int i = 0; i < destinationsBCc.length; i++)
            addressBCc[i] = new InternetAddress(destinationsBCc[i]);

        msg.setRecipients(Message.RecipientType.BCC, addressBCc);
    }

    if (mailsubject != null)
        msg.setSubject(mailsubject);

    msg.setSentDate(new Date());
    StringBuffer messageText = new StringBuffer();

    if (comment != null)
        messageText.append(comment).append(Const.CR).append(Const.CR);

    if (meta.getIncludeDate())
        messageText.append(Messages.getString("Mail.Log.Comment.MsgDate") + ": ")
                .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);

    if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) {
        messageText.append(Messages.getString("Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
        messageText.append("---------------------").append(Const.CR);
        messageText.append(Messages.getString("Mail.Log.Comment.PersonToContact") + " : ").append(contactPerson)
                .append(Const.CR);
        messageText.append(Messages.getString("Mail.Log.Comment.Tel") + "  : ").append(contactPhone)
                .append(Const.CR);
        messageText.append(Const.CR);
    }
    data.parts = new MimeMultipart();

    MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
    // 1st part

    if (meta.isUseHTML()) {
        if (!Const.isEmpty(meta.getEncoding()))
            part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding());
        else
            part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
    } else
        part1.setText(messageText.toString());

    data.parts.addBodyPart(part1);

    // attached files
    if (meta.isDynamicFilename())
        setAttachedFilesList(r, log);
    else
        setAttachedFilesList(null, log);

    msg.setContent(data.parts);

    Transport transport = null;
    try {
        transport = session.getTransport(protocol);
        if (meta.isUsingAuthentication()) {
            if (!Const.isEmpty(port)) {
                transport.connect(Const.NVL(server, ""), Integer.parseInt(Const.NVL(port, "")),
                        Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, ""));
            } else {
                transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            }
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (transport != null)
            transport.close();
    }

}

From source file:org.exist.xquery.modules.mail.SendEmailFunction.java

public Sequence sendEmail(Sequence[] args, Sequence contextSequence) throws XPathException {
    // was a session handle specified?
    if (args[0].isEmpty()) {
        throw (new XPathException(this, "Session handle not specified"));
    }/* www . ja va  2s.c  om*/

    // get the Session
    long sessionHandle = ((IntegerValue) args[0].itemAt(0)).getLong();
    Session session = MailModule.retrieveSession(context, sessionHandle);
    if (session == null) {
        throw (new XPathException(this, "Invalid Session handle specified"));
    }

    try {
        List<Message> messages = parseInputEmails(session, args[1]);
        String proto = session.getProperty("mail.transport.protocol");
        if (proto == null)
            proto = "smtp";
        Transport t = session.getTransport(proto);
        try {
            if (session.getProperty("mail." + proto + ".auth") != null)
                t.connect(session.getProperty("mail." + proto + ".user"),
                        session.getProperty("mail." + proto + ".password"));
            for (Message msg : messages) {
                t.sendMessage(msg, msg.getAllRecipients());
            }
        } finally {
            t.close();
        }

        return (Sequence.EMPTY_SEQUENCE);
    } catch (TransformerException te) {
        throw new XPathException(this, "Could not Transform XHTML Message Body: " + te.getMessage(), te);
    } catch (MessagingException smtpe) {
        throw new XPathException(this, "Could not send message(s): " + smtpe.getMessage(), smtpe);
    } catch (IOException ioe) {
        throw new XPathException(this, "Attachment in some message could not be prepared: " + ioe.getMessage(),
                ioe);
    } catch (Throwable t) {
        throw new XPathException(this,
                "Unexpected error from JavaMail layer (Is your message well structured?): " + t.getMessage(),
                t);
    }
}

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  w  w w.  j  av a2  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:com.thoughtworks.go.config.GoSmtpMailSender.java

public ValidationBean send(String subject, String body, String to) {
    Transport transport = null;
    try {//from w  w w  .  j  a va 2 s.c o  m
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Sending email [%s] to [%s]", subject, to));
        }
        Properties props = mailProperties();
        MailSession session = MailSession.getInstance().createWith(props, username, password);
        transport = session.getTransport();
        transport.connect(host, port, nullIfEmpty(username), nullIfEmpty(password));
        MimeMessage msg = session.createMessage(from, to, subject, body);
        transport.sendMessage(msg, msg.getRecipients(TO));
        return ValidationBean.valid();
    } catch (AuthenticationFailedException e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: Authentication failed");
    } catch (NoSuchProviderException e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage());
    } catch (MessagingException e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage());
    } catch (Exception e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage());
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (MessagingException e) {
                LOGGER.error("Failed to close transport", e);
            }
        }
    }
}

From source file:org.pentaho.di.trans.steps.mail.Mail.java

public void sendMail(Object[] r, String server, int port, String senderAddress, String senderName,
        String destination, String destinationCc, String destinationBCc, String contactPerson,
        String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject,
        String comment, String replyToAddresses) throws Exception {

    // Send an e-mail...
    // create some properties and get the default Session

    String protocol = "smtp";
    if (meta.isUsingSecureAuthentication()) { // PDI-2955
        // if (meta.isUsingAuthentication()) {
        if (meta.getSecureConnectionType().equals("TLS")) {
            // Allow TLS authentication
            data.props.put("mail.smtp.starttls.enable", "true");
        } else {/* www.j  ava  2  s . c  om*/
            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version Unknown
            data.props.put("mail.smtps.quitwait", "false");
        }
    }
    data.props.put("mail." + protocol + ".host", server);
    if (port != -1) {
        data.props.put("mail." + protocol + ".port", "" + port); // needs to be supplied as a string, not as an integer
    }

    if (isDebug()) {
        data.props.put("mail.debug", "true");
    }

    if (meta.isUsingAuthentication()) {
        data.props.put("mail." + protocol + ".auth", "true");
    }

    Session session = Session.getInstance(data.props);
    session.setDebug(isDebug());

    // create a message
    Message msg = new MimeMessage(session);

    // set message priority
    if (meta.isUsePriority()) {
        String priority_int = "1";
        if (meta.getPriority().equals("low")) {
            priority_int = "3";
        }
        if (meta.getPriority().equals("normal")) {
            priority_int = "2";
        }

        msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low.
        msg.setHeader("Importance", meta.getImportance());
        // seems to be needed for MS Outlook.
        // where it returns a string of high /normal /low.
        msg.setHeader("Sensitivity", meta.getSensitivity());
        // Possible values are normal, personal, private, company-confidential
    }

    // set Email sender
    String email_address = senderAddress;
    if (!Const.isEmpty(email_address)) {
        // get sender name
        if (!Const.isEmpty(senderName)) {
            email_address = senderName + '<' + email_address + '>';
        }
        msg.setFrom(new InternetAddress(email_address));
    } else {
        throw new MessagingException(BaseMessages.getString(PKG, "Mail.Error.ReplyEmailNotFilled"));
    }

    // Set reply to
    if (!Const.isEmpty(replyToAddresses)) {
        // get replay to
        // Split the mail-address: space separated
        String[] reply_Address_List = replyToAddresses.split(" ");
        InternetAddress[] address = new InternetAddress[reply_Address_List.length];

        for (int i = 0; i < reply_Address_List.length; i++) {
            address[i] = new InternetAddress(reply_Address_List[i]);
        }

        // To add the real reply-to
        msg.setReplyTo(address);
    }

    // Split the mail-address: space separated
    String[] destinations = destination.split(" ");
    InternetAddress[] address = new InternetAddress[destinations.length];
    for (int i = 0; i < destinations.length; i++) {
        address[i] = new InternetAddress(destinations[i]);
    }

    msg.setRecipients(Message.RecipientType.TO, address);

    String realdestinationCc = destinationCc;
    if (!Const.isEmpty(realdestinationCc)) {
        // Split the mail-address Cc: space separated
        String[] destinationsCc = realdestinationCc.split(" ");
        InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
        for (int i = 0; i < destinationsCc.length; i++) {
            addressCc[i] = new InternetAddress(destinationsCc[i]);
        }

        msg.setRecipients(Message.RecipientType.CC, addressCc);
    }

    String realdestinationBCc = destinationBCc;
    if (!Const.isEmpty(realdestinationBCc)) {
        // Split the mail-address BCc: space separated
        String[] destinationsBCc = realdestinationBCc.split(" ");
        InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
        for (int i = 0; i < destinationsBCc.length; i++) {
            addressBCc[i] = new InternetAddress(destinationsBCc[i]);
        }

        msg.setRecipients(Message.RecipientType.BCC, addressBCc);
    }

    if (mailsubject != null) {
        msg.setSubject(mailsubject);
    }

    msg.setSentDate(new Date());
    StringBuffer messageText = new StringBuffer();

    if (comment != null) {
        messageText.append(comment).append(Const.CR).append(Const.CR);
    }

    if (meta.getIncludeDate()) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.MsgDate") + ": ")
                .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
    }

    if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
        messageText.append("---------------------").append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.PersonToContact") + " : ")
                .append(contactPerson).append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.Tel") + "  : ").append(contactPhone)
                .append(Const.CR);
        messageText.append(Const.CR);
    }
    data.parts = new MimeMultipart();

    MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
    // 1st part

    if (meta.isUseHTML()) {
        if (!Const.isEmpty(meta.getEncoding())) {
            part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding());
        } else {
            part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
        }
    } else {
        part1.setText(messageText.toString());
    }

    data.parts.addBodyPart(part1);

    if (meta.isAttachContentFromField()) {
        // attache file content
        addAttachedContent(data.previousRowMeta.getString(r, data.IndexOfAttachedFilename),
                data.previousRowMeta.getString(r, data.indexOfAttachedContent));
    } else {
        // attached files
        if (meta.isDynamicFilename()) {
            setAttachedFilesList(r, log);
        } else {
            setAttachedFilesList(null, log);
        }
    }

    // add embedded images
    addImagePart();

    if (data.nrEmbeddedImages > 0 && data.nrattachedFiles == 0) {
        // If we need to embedd images...
        // We need to create a "multipart/related" message.
        // otherwise image will appear as attached file
        data.parts.setSubType("related");
    }

    msg.setContent(data.parts);

    Transport transport = null;
    try {
        transport = session.getTransport(protocol);
        if (meta.isUsingAuthentication()) {
            if (port != -1) {
                transport.connect(Const.NVL(server, ""), port, Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            } else {
                transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            }
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (transport != null) {
            transport.close();
        }
    }

}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments)
        throws MessagingException {
    Transport t = null;

    try {//from w w w .j  a v  a2s .c  o m
        MimeMessage message = new MimeMessage(session);

        t = session.getTransport("smtp");

        message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        if (attachments == null || attachments.size() < 1) {
            message.setText(text);
        } else {
            // create the message part 
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(text);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            try {
                for (InputStream attachment : attachments.keySet()) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");

                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR 
                    multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val
                }
            } catch (IOException e) {
                throw new MessagingException("cannot add an attachment to mail", e);
            }
            message.setContent(multipart);
        }

        t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

        t.sendMessage(message, message.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }

}