Example usage for javax.mail SendFailedException getValidSentAddresses

List of usage examples for javax.mail SendFailedException getValidSentAddresses

Introduction

In this page you can find the example usage for javax.mail SendFailedException getValidSentAddresses.

Prototype

public Address[] getValidSentAddresses() 

Source Link

Document

Return the addresses to which this message was sent succesfully.

Usage

From source file:msgsendsample.java

public static void main(String[] args) {
    if (args.length != 4) {
        usage();/*from  www .j  av a2  s .  c om*/
        System.exit(1);
    }

    System.out.println();

    String to = args[0];
    String from = args[1];
    String host = args[2];
    boolean debug = Boolean.valueOf(args[3]).booleanValue();

    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    if (debug)
        props.put("mail.debug", args[3]);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail APIs Test");
        msg.setSentDate(new Date());
        // If the desired charset is known, you can use
        // setText(text, charset)
        msg.setText(msgText);

        Transport.send(msg);
    } catch (MessagingException mex) {
        System.out.println("\n--Exception handling in msgsendsample.java");

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++)
                        System.out.println("         " + invalid[i]);
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++)
                        System.out.println("         " + validUnsent[i]);
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++)
                        System.out.println("         " + validSent[i]);
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    if (args.length != 4) {
        usage();/*from w w w .  j a va  2s .  co m*/
        System.exit(1);
    }

    System.out.println();

    String to = args[0];
    String from = args[1];
    String host = args[2];
    boolean debug = Boolean.valueOf(args[3]).booleanValue();

    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    if (debug)
        props.put("mail.debug", args[3]);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(args[0]) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail APIs Test");
        msg.setSentDate(new Date());
        // If the desired charset is known, you can use
        // setText(text, charset)
        msg.setText(msgText);

        Transport.send(msg);
    } catch (MessagingException mex) {
        System.out.println("\n--Exception handling in msgsendsample.java");

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    if (invalid != null) {
                        for (int i = 0; i < invalid.length; i++)
                            System.out.println("         " + invalid[i]);
                    }
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++)
                            System.out.println("         " + validUnsent[i]);
                    }
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    if (validSent != null) {
                        for (int i = 0; i < validSent.length; i++)
                            System.out.println("         " + validSent[i]);
                    }
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}

From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java

@Test(timeout = 3000)
public void mailFromError() throws Exception {
    server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO
            .sendLine("250 OK").recvLine() // MAIL FROM
            .sendLine("451 error").recvLine() // QUIT
            .build().start(PORT);//  w w  w  .ja  v a 2 s.  c om

    Session session = JMSession.getSession();
    Transport transport = session.getTransport("smtp");
    transport.connect("localhost", PORT, null, null);
    String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\n" + "Subject: test\n\ntest";
    MimeMessage msg = new ZMimeMessage(session,
            new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1)));
    try {
        transport.sendMessage(msg, msg.getAllRecipients());
        Assert.fail();
    } catch (SendFailedException e) {
        Assert.assertEquals(0, e.getValidSentAddresses().length);
        Assert.assertEquals(0, e.getValidUnsentAddresses().length);
        Assert.assertEquals(0, e.getInvalidAddresses().length);
    } finally {
        transport.close();
    }

    server.shutdown(1000);
    Assert.assertEquals("EHLO localhost\r\n", server.replay());
    Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("QUIT\r\n", server.replay());
    Assert.assertNull(server.replay());
}

From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java

@Test(timeout = 3000)
public void rcptToError() throws Exception {
    server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO
            .sendLine("250 OK").recvLine() // MAIL FROM
            .sendLine("250 OK").recvLine() // RCPT TO
            .sendLine("550 error").recvLine() // QUIT
            .build().start(PORT);/*from  w w  w  .  j a  v a 2s .c  o  m*/

    Session session = JMSession.getSession();
    session.getProperties().setProperty("mail.smtp.sendpartial", "true");
    Transport transport = session.getTransport("smtp");
    transport.connect("localhost", PORT, null, null);
    String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest";
    MimeMessage msg = new ZMimeMessage(session,
            new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1)));
    try {
        transport.sendMessage(msg, msg.getAllRecipients());
        Assert.fail();
    } catch (SendFailedException e) {
        Assert.assertEquals(0, e.getValidSentAddresses().length);
        Assert.assertEquals(0, e.getValidUnsentAddresses().length);
        Assert.assertEquals(1, e.getInvalidAddresses().length);
    } finally {
        transport.close();
    }

    server.shutdown(1000);
    Assert.assertEquals("EHLO localhost\r\n", server.replay());
    Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("QUIT\r\n", server.replay());
    Assert.assertNull(server.replay());
}

From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java

@Test(timeout = 3000)
public void dataError() throws Exception {
    server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO
            .sendLine("250 OK").recvLine() // MAIL FROM
            .sendLine("250 OK").recvLine() // RCPT TO
            .sendLine("250 OK").recvLine() // DATA
            .sendLine("451 error").recvLine() // QUIT
            .build().start(PORT);//from w  w w.j  av  a  2 s .  c o  m

    Session session = JMSession.getSession();
    Transport transport = session.getTransport("smtp");
    transport.connect("localhost", PORT, null, null);
    String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest";
    MimeMessage msg = new ZMimeMessage(session,
            new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1)));
    try {
        transport.sendMessage(msg, msg.getAllRecipients());
        Assert.fail();
    } catch (SendFailedException e) {
        Assert.assertEquals(1, e.getValidSentAddresses().length);
        Assert.assertEquals(0, e.getValidUnsentAddresses().length);
        Assert.assertEquals(0, e.getInvalidAddresses().length);
    } finally {
        transport.close();
    }

    server.shutdown(1000);
    Assert.assertEquals("EHLO localhost\r\n", server.replay());
    Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("DATA\r\n", server.replay());
    Assert.assertEquals("QUIT\r\n", server.replay());
    Assert.assertNull(server.replay());
}

From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java

@Test(timeout = 3000)
public void sendPartially() throws Exception {
    server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO
            .sendLine("250 OK").recvLine() // MAIL FROM
            .sendLine("250 OK").recvLine() // RCPT TO 1
            .sendLine("250 OK").recvLine() // RCPT TO 2
            .sendLine("550 not found").recvLine() // RCPT TO 3
            .sendLine("550 not found").recvLine() // DATA
            .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT
            .sendLine("221 bye").build().start(PORT);

    Session session = JMSession.getSession();
    session.getProperties().setProperty("mail.smtp.sendpartial", "true");
    Transport transport = session.getTransport("smtp");
    transport.connect("localhost", PORT, null, null);
    String raw = "From: sender@zimbra.com\n"
            + "To: rcpt1@zimbra.com, rcpt2@zimbra.com, rcpt3@zimbra.com\nSubject: test\n\ntest";
    MimeMessage msg = new ZMimeMessage(session,
            new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1)));
    try {/*  w  ww .  ja  v a  2 s. c o m*/
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (SendFailedException e) {
        Assert.assertEquals(1, e.getValidSentAddresses().length);
        Assert.assertEquals(0, e.getValidUnsentAddresses().length);
        Assert.assertEquals(2, e.getInvalidAddresses().length);
    } finally {
        transport.close();
    }

    server.shutdown(1000);
    Assert.assertEquals("EHLO localhost\r\n", server.replay());
    Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("RCPT TO:<rcpt1@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("RCPT TO:<rcpt2@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("RCPT TO:<rcpt3@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("DATA\r\n", server.replay());
    Assert.assertEquals("QUIT\r\n", server.replay());
    Assert.assertNull(server.replay());
}

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.j  av  a  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:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;/* www.  ja v a2s.  co  m*/

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, toAddr);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setSentDate(new Date()); // Date: header
        msg.setContent(msgText + msgText2, "text/plain");
        msg.saveChanges();

        // get the smtp transport for the address
        trans = session.getTransport(toAddr[0]);

        // register ourselves as listener for ConnectionEvents 
        // and TransportEvents
        trans.addConnectionListener(this);
        trans.addTransportListener(this);

        // connect the transport
        trans.connect();

        // send the message
        trans.sendMessage(msg, toAddr);

        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

    } catch (MessagingException mex) {
        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

        System.out.println("Sending failed with exception:");
        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++)
                        System.out.println("         " + invalid[i]);
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++)
                        System.out.println("         " + validUnsent[i]);
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++)
                        System.out.println("         " + validSent[i]);
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    } finally {
        try {
            // close the transport
            if (trans != null)
                trans.close();
        } catch (MessagingException mex) {
            /* ignore */ }
    }
}

From source file:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;/*  w ww .ja va  2  s.c  o  m*/

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, toAddr);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setSentDate(new Date()); // Date: header
        msg.setContent(msgText + msgText2, "text/plain");
        msg.saveChanges();

        // get the smtp transport for the address
        trans = session.getTransport(toAddr[0]);

        // register ourselves as listener for ConnectionEvents
        // and TransportEvents
        trans.addConnectionListener(this);
        trans.addTransportListener(this);

        // connect the transport
        trans.connect();

        // send the message
        trans.sendMessage(msg, toAddr);

        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

    } catch (MessagingException mex) {
        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    if (invalid != null) {
                        for (int i = 0; i < invalid.length; i++)
                            System.out.println("         " + invalid[i]);
                    }
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++)
                            System.out.println("         " + validUnsent[i]);
                    }
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    if (validSent != null) {
                        for (int i = 0; i < validSent.length; i++)
                            System.out.println("         " + validSent[i]);
                    }
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    } finally {
        try {
            // close the transport
            trans.close();
        } catch (MessagingException mex) { /* ignore */
        }
    }
}

From source file:com.youxifan.utils.EMail.java

/**
 *   Send Mail direct/*from   w w w.jav  a 2 s. c  o  m*/
 *   @return OK or error message
 */
public String send() {
    log.info("(" + m_smtpHost + ") " + m_from + " -> " + m_to);
    m_sentMsg = null;
    //
    if (!isValid(true)) {
        m_sentMsg = "Invalid Data";
        return m_sentMsg;
    }
    //
    Properties props = System.getProperties();
    props.put("mail.store.protocol", "smtp");
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.host", m_smtpHost);
    //   Bit-Florin David
    props.put("mail.smtp.port", String.valueOf(m_smtpPort));
    //   TLS settings
    if (m_isSmtpTLS) {
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.port", String.valueOf(m_smtpPort));
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
    }

    //
    Session session = null;
    try {
        if (m_auth != null) //   createAuthenticator was called
            props.put("mail.smtp.auth", "true");
        //         if (m_smtpHost.equalsIgnoreCase("smtp.gmail.com")) {
        //            // TODO: make it configurable
        //            // Enable gmail port and ttls - Hardcoded
        //            props.put("mail.smtp.port", "587");
        //            props.put("mail.smtp.starttls.enable", "true");
        //         }

        session = Session.getInstance(props, m_auth);
    } catch (SecurityException se) {
        log.warn("Auth=" + m_auth + " - " + se.toString());
        m_sentMsg = se.toString();
        return se.toString();
    } catch (Exception e) {
        log.warn("Auth=" + m_auth, e);
        m_sentMsg = e.toString();
        return e.toString();
    }

    try {
        //   m_msg = new MimeMessage(session);
        m_msg = new SMTPMessage(session);
        //   Addresses
        m_msg.setFrom(m_from);
        InternetAddress[] rec = getTos();
        if (rec.length == 1)
            m_msg.setRecipient(Message.RecipientType.TO, rec[0]);
        else
            m_msg.setRecipients(Message.RecipientType.TO, rec);
        rec = getCcs();
        if (rec != null && rec.length > 0)
            m_msg.setRecipients(Message.RecipientType.CC, rec);
        rec = getBccs();
        if (rec != null && rec.length > 0)
            m_msg.setRecipients(Message.RecipientType.BCC, rec);
        if (m_replyTo != null)
            m_msg.setReplyTo(new Address[] { m_replyTo });
        //
        m_msg.setSentDate(new java.util.Date());
        m_msg.setHeader("Comments", "Becit Mail");
        m_msg.setHeader("Comments", "Becit ERP Mail");
        //   m_msg.setDescription("Description");
        //   SMTP specifics
        m_msg.setAllow8bitMIME(true);
        //   Send notification on Failure & Success - no way to set envid in Java yet
        //   m_msg.setNotifyOptions (SMTPMessage.NOTIFY_FAILURE | SMTPMessage.NOTIFY_SUCCESS);
        //   Bounce only header
        m_msg.setReturnOption(SMTPMessage.RETURN_HDRS);
        //   m_msg.setHeader("X-Mailer", "msgsend");
        //
        setContent();
        m_msg.saveChanges();
        //   log.fine("message =" + m_msg);
        //
        //   Transport.send(msg);
        Transport t = session.getTransport("smtp");
        //   log.fine("transport=" + t);
        t.connect();
        //   t.connect(m_smtpHost, user, password);
        //   log.fine("transport connected");
        Transport.send(m_msg);
        //   t.sendMessage(msg, msg.getAllRecipients());
        log.info("Success - MessageID=" + m_msg.getMessageID());
    } catch (MessagingException me) {
        Exception ex = me;
        StringBuffer sb = new StringBuffer("(ME)");
        boolean printed = false;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (!printed) {
                    if (invalid != null && invalid.length > 0) {
                        sb.append(" - Invalid:");
                        for (int i = 0; i < invalid.length; i++)
                            sb.append(" ").append(invalid[i]);

                    }
                    Address[] validUnsent = sfex.getValidUnsentAddresses();
                    if (validUnsent != null && validUnsent.length > 0) {
                        sb.append(" - ValidUnsent:");
                        for (int i = 0; i < validUnsent.length; i++)
                            sb.append(" ").append(validUnsent[i]);
                    }
                    Address[] validSent = sfex.getValidSentAddresses();
                    if (validSent != null && validSent.length > 0) {
                        sb.append(" - ValidSent:");
                        for (int i = 0; i < validSent.length; i++)
                            sb.append(" ").append(validSent[i]);
                    }
                    printed = true;
                }
                if (sfex.getNextException() == null)
                    sb.append(" ").append(sfex.getLocalizedMessage());
            } else if (ex instanceof AuthenticationFailedException) {
                sb.append(" - Invalid Username/Password - " + m_auth);
            } else //   other MessagingException 
            {
                String msg = ex.getLocalizedMessage();
                if (msg == null)
                    sb.append(": ").append(ex.toString());
                else {
                    if (msg.indexOf("Could not connect to SMTP host:") != -1) {
                        int index = msg.indexOf('\n');
                        if (index != -1)
                            msg = msg.substring(0, index);
                        String cc = "??";

                        msg += " - AD_Client_ID=" + cc;
                    }
                    String className = ex.getClass().getName();
                    if (className.indexOf("MessagingException") != -1)
                        sb.append(": ").append(msg);
                    else
                        sb.append(" ").append(className).append(": ").append(msg);
                }
            }
            //   Next Exception
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null); //   error loop
        m_sentMsg = sb.toString();
        return sb.toString();
    } catch (Exception e) {
        log.warn("", e);
        m_sentMsg = e.getLocalizedMessage();
        return e.getLocalizedMessage();
    }
    //
    m_sentMsg = SENT_OK;
    return m_sentMsg;
}