Example usage for javax.mail SendFailedException getValidUnsentAddresses

List of usage examples for javax.mail SendFailedException getValidUnsentAddresses

Introduction

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

Prototype

public Address[] getValidUnsentAddresses() 

Source Link

Document

Return the addresses that are valid but to which this message was not sent.

Usage

From source file:msgsendsample.java

public static void main(String[] args) {
    if (args.length != 4) {
        usage();//ww w .  j  a v  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 ww .  ja v a 2s. 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
        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.sun.socialsite.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.//from   w w w .  ja v  a2  s  . com
 *
 * @param from e-mail address of sender
 * @param to e-mail address(es) of recipients
 * @param subject subject of e-mail
 * @param content the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    Message message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled())
            mLogger.debug("e-mail from: " + sentFrom);
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("sending e-mail to: " + to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("copying e-mail to: " + cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject);
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Startup.getMailProvider().getTransport().sendMessage(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome)
        throw sendex;
}

From source file:com.hg.ecommerce.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.//from www.ja v a  2s  .  c  om
 *
 * @param from     e-mail address of sender
 * @param to       e-mail address(es) of recipients
 * @param subject  subject of e-mail
 * @param content  the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    MimeMessage message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled()) {
            mLogger.debug("e-mail from: " + sentFrom);
        }
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("sending e-mail to: " + to[i]);
            }
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("copying e-mail to: " + cc[i]);
            }
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
            }
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject, "UTF-8");
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Transport.send(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome) {
        throw sendex;
    }
}

From source file:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;/*from w w w  .  jav a 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) {
        }

        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: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);/*from   www  . j  ava  2s  . co 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\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);/*ww w.ja  v  a 2 s. 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  a v  a2s  .co  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 {//from   w w  w. j av  a2  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:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;/*from w  ww . jav a2  s .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) {
        }

        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 */
        }
    }
}