Search in sources :

Example 1 with SMTPAddressSucceededException

use of com.sun.mail.smtp.SMTPAddressSucceededException in project ph-web by phax.

the class MailTransport method send.

/**
 * Actually send the given array of MimeMessages via JavaMail.
 *
 * @param aAllMessages
 *        Email data objects to send. May be <code>null</code>.
 * @return A non-<code>null</code> map of the failed messages
 */
@Nonnull
public ICommonsOrderedMap<IMutableEmailData, MailTransportError> send(@Nullable final Collection<IMutableEmailData> aAllMessages) {
    final ICommonsOrderedMap<IMutableEmailData, MailTransportError> aFailedMessages = new CommonsLinkedHashMap<>();
    if (aAllMessages != null) {
        final ICommonsList<IMutableEmailData> aRemainingMessages = new CommonsArrayList<>(aAllMessages);
        MailSendException aExceptionToBeRemembered = null;
        try (final Transport aTransport = m_aSession.getTransport(m_bSMTPS ? SMTPS_PROTOCOL : SMTP_PROTOCOL)) {
            // Add global listeners (if present)
            for (final ConnectionListener aConnectionListener : EmailGlobalSettings.getAllConnectionListeners()) aTransport.addConnectionListener(aConnectionListener);
            // Check if a detailed listener is present
            final ICommonsList<IEmailDataTransportListener> aEmailDataTransportListeners = EmailGlobalSettings.getAllEmailDataTransportListeners();
            // Connect
            aTransport.connect(m_aSMTPSettings.getHostName(), m_aSMTPSettings.getPort(), m_aSMTPSettings.getUserName(), m_aSMTPSettings.getPassword());
            // For all messages
            for (final IMutableEmailData aEmailData : aAllMessages) {
                final MimeMessage aMimeMessage = new MimeMessage(m_aSession);
                try {
                    // convert from IEmailData to MimeMessage
                    MailConverter.fillMimeMessage(aMimeMessage, aEmailData, m_aSMTPSettings.getCharsetObj());
                    // Ensure a sent date is present
                    if (aMimeMessage.getSentDate() == null)
                        aMimeMessage.setSentDate(new Date());
                    // Get an explicitly specified message ID
                    final String sMessageID = aMimeMessage.getMessageID();
                    // This creates a new message ID (besides other things)
                    aMimeMessage.saveChanges();
                    if (sMessageID != null) {
                        // Preserve explicitly specified message id...
                        aMimeMessage.setHeader(HEADER_MESSAGE_ID, sMessageID);
                    }
                    aMimeMessage.setHeader(HEADER_X_MAILER, X_MAILER);
                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("Delivering mail from " + Arrays.toString(aMimeMessage.getFrom()) + " to " + Arrays.toString(aMimeMessage.getAllRecipients()) + " with subject '" + aMimeMessage.getSubject() + "' and message ID '" + aMimeMessage.getMessageID() + "'");
                    // Main transmit - always throws an exception
                    aTransport.sendMessage(aMimeMessage, aMimeMessage.getAllRecipients());
                    throw new IllegalStateException("Never expected to come beyong sendMessage!");
                } catch (final SendFailedException ex) {
                    if (EmailGlobalSettings.isDebugSMTP())
                        LOGGER.error("Error send mail - SendFailedException", ex);
                    /*
             * Extract all addresses: the valid addresses to which the message
             * was sent, the valid address to which the message was not sent and
             * the invalid addresses
             */
                    final ICommonsSet<String> aValidSent = new CommonsHashSet<>(ex.getValidSentAddresses(), Address::toString);
                    final ICommonsSet<String> aValidUnsent = new CommonsHashSet<>(ex.getValidUnsentAddresses(), Address::toString);
                    final ICommonsSet<String> aInvalid = new CommonsHashSet<>(ex.getInvalidAddresses(), Address::toString);
                    final ICommonsList<MailSendDetails> aDetails = new CommonsArrayList<>();
                    Exception ex2;
                    MessagingException bex = ex;
                    while ((ex2 = bex.getNextException()) != null && ex2 instanceof MessagingException) {
                        if (ex2 instanceof SMTPAddressFailedException) {
                            final SMTPAddressFailedException ssfe = (SMTPAddressFailedException) ex2;
                            aDetails.add(new MailSendDetails(false, ssfe.getAddress().toString(), ssfe.getCommand(), ssfe.getMessage().trim(), ESMTPErrorCode.getFromIDOrDefault(ssfe.getReturnCode(), ESMTPErrorCode.FALLBACK)));
                        } else if (ex2 instanceof SMTPAddressSucceededException) {
                            final SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) ex2;
                            aDetails.add(new MailSendDetails(true, ssfe.getAddress().toString(), ssfe.getCommand(), ssfe.getMessage().trim(), ESMTPErrorCode.getFromIDOrDefault(ssfe.getReturnCode(), ESMTPErrorCode.FALLBACK)));
                        }
                        bex = (MessagingException) ex2;
                    }
                    // Map addresses to details
                    final ICommonsOrderedSet<MailSendDetails> aValidSentExt = new CommonsLinkedHashSet<>();
                    final ICommonsOrderedSet<MailSendDetails> aValidUnsentExt = new CommonsLinkedHashSet<>();
                    final ICommonsOrderedSet<MailSendDetails> aInvalidExt = new CommonsLinkedHashSet<>();
                    for (final MailSendDetails aFailure : aDetails) {
                        final String sAddress = aFailure.getAddress();
                        if (aValidSent.contains(sAddress))
                            aValidSentExt.add(aFailure);
                        else if (aValidUnsent.contains(sAddress))
                            aValidUnsentExt.add(aFailure);
                        else
                            aInvalidExt.add(aFailure);
                    }
                    final EmailDataTransportEvent aEvent = new EmailDataTransportEvent(m_aSMTPSettings, aEmailData, aMimeMessage, aValidSentExt, aValidUnsentExt, aInvalidExt);
                    if (aValidUnsent.isEmpty() && aInvalid.isEmpty() && aValidSent.isNotEmpty()) {
                        // Message delivered
                        for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners) aEmailDataTransportListener.messageDelivered(aEvent);
                        // Remove message from list of remaining
                        STATS_SEND_SUCCESS.increment();
                    } else {
                        // Message not delivered
                        for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners) aEmailDataTransportListener.messageNotDelivered(aEvent);
                        // Sending exactly this message failed
                        aFailedMessages.put(aEmailData, new MailTransportError(ex, aDetails));
                        STATS_SEND_FAILURE.increment();
                    }
                    // Remove message from list of remaining as we put it in the
                    // failed message list manually in case of error
                    aRemainingMessages.remove(aEmailData);
                } catch (final MessagingException ex) {
                    if (EmailGlobalSettings.isDebugSMTP())
                        LOGGER.error("Error send mail - MessagingException", ex);
                    final ICommonsOrderedSet<MailSendDetails> aInvalid = new CommonsLinkedHashSet<>();
                    final Consumer<IEmailAddress> aConsumer = a -> aInvalid.add(new MailSendDetails(false, a.getAddress(), "<generic error>", ex.getMessage(), ESMTPErrorCode.FALLBACK));
                    aEmailData.to().forEach(aConsumer);
                    aEmailData.cc().forEach(aConsumer);
                    aEmailData.bcc().forEach(aConsumer);
                    final EmailDataTransportEvent aEvent = new EmailDataTransportEvent(m_aSMTPSettings, aEmailData, aMimeMessage, new CommonsArrayList<>(), new CommonsArrayList<>(), aInvalid);
                    // Message not delivered
                    for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners) aEmailDataTransportListener.messageNotDelivered(aEvent);
                    // Sending exactly this message failed
                    aFailedMessages.put(aEmailData, new MailTransportError(ex));
                    // Remove message from list of remaining as we put it in the
                    // failed message list manually
                    aRemainingMessages.remove(aEmailData);
                    STATS_SEND_FAILURE.increment();
                }
            }
        // for all messages
        } catch (final AuthenticationFailedException ex) {
            // problem with the credentials
            aExceptionToBeRemembered = new MailSendException("Mail server authentication failed", ex);
        } catch (final MessagingException ex) {
            if (WebExceptionHelper.isServerNotReachableConnection(ex.getCause()))
                aExceptionToBeRemembered = new MailSendException("Failed to connect to mail server: " + ex.getCause().getMessage());
            else
                aExceptionToBeRemembered = new MailSendException("Mail server connection failed", ex);
        } catch (final Exception ex) {
            // E.g. IllegalState from SMTPTransport ("Not connected")
            aExceptionToBeRemembered = new MailSendException("Internal error sending mail", ex);
        } finally {
            // Was any message not sent
            if (aRemainingMessages.isNotEmpty()) {
                if (aExceptionToBeRemembered == null)
                    aExceptionToBeRemembered = new MailSendException("Internal error - messages are remaining but no Exception occurred!");
                for (final IMutableEmailData aRemainingMessage : aRemainingMessages) aFailedMessages.put(aRemainingMessage, new MailTransportError(aExceptionToBeRemembered));
            }
        }
    }
    return aFailedMessages;
}
Also used : ICommonsList(com.helger.commons.collection.impl.ICommonsList) AuthenticationFailedException(javax.mail.AuthenticationFailedException) EmailDataTransportEvent(com.helger.smtp.listener.EmailDataTransportEvent) IMutableEmailData(com.helger.smtp.data.IMutableEmailData) ICommonsOrderedSet(com.helger.commons.collection.impl.ICommonsOrderedSet) ConnectionListener(javax.mail.event.ConnectionListener) Consumer(java.util.function.Consumer) MimeMessage(javax.mail.internet.MimeMessage) IEmailDataTransportListener(com.helger.smtp.listener.IEmailDataTransportListener) CommonsLinkedHashMap(com.helger.commons.collection.impl.CommonsLinkedHashMap) SendFailedException(javax.mail.SendFailedException) MessagingException(javax.mail.MessagingException) SMTPAddressFailedException(com.sun.mail.smtp.SMTPAddressFailedException) SMTPAddressSucceededException(com.sun.mail.smtp.SMTPAddressSucceededException) Date(java.util.Date) MessagingException(javax.mail.MessagingException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) SendFailedException(javax.mail.SendFailedException) SMTPAddressFailedException(com.sun.mail.smtp.SMTPAddressFailedException) SMTPAddressSucceededException(com.sun.mail.smtp.SMTPAddressSucceededException) ICommonsSet(com.helger.commons.collection.impl.ICommonsSet) Transport(javax.mail.Transport) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) Nonnull(javax.annotation.Nonnull)

Example 2 with SMTPAddressSucceededException

use of com.sun.mail.smtp.SMTPAddressSucceededException in project ph-web by phax.

the class MainSMTPSend method main.

/*
   * Example of how to extend the SMTPTransport class. This example illustrates
   * how to issue the XACT command before the SMTPTransport issues the DATA
   * command. public static class SMTPExtension extends SMTPTransport { public
   * SMTPExtension(Session session, URLName url) { super(session, url); // to
   * check that we're being used System.out.println("SMTPExtension: constructed"
   * ); } protected synchronized OutputStream data() throws MessagingException {
   * if (supportsExtension("XACCOUNTING")) issueCommand("XACT", 250); return
   * super.data(); } }
   */
@SuppressWarnings("resource")
public static void main(final String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;
    final String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    // name of folder in which to record mail
    String record = null;
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    String prot = "smtp";
    final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;
    /*
     * Process command line arguments.
     */
    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) {
            // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-A")) {
            auth = true;
        } else if (argv[optind].equals("-S")) {
            prot = "smtps";
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
            System.out.println("\t[-v] [-A] [-S] [address]");
            System.exit(1);
        } else {
            break;
        }
    }
    try {
        /*
       * Prompt for To and Subject, if not specified.
       */
        if (optind < argv.length) {
            // - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }
        /*
       * Initialize the JavaMail Session.
       */
        final Properties props = IPrivilegedAction.systemGetProperties().invokeSafe();
        if (mailhost != null)
            props.put("mail." + prot + ".host", mailhost);
        if (auth)
            props.put("mail." + prot + ".auth", "true");
        /*
       * Create a Provider representing our extended SMTP transport and set the
       * property to use our provider. Provider p = new
       * Provider(Provider.Type.TRANSPORT, prot, "smtpsend$SMTPExtension",
       * "JavaMail demo", "no version"); props.put("mail." + prot + ".class",
       * "smtpsend$SMTPExtension");
       */
        // Get a Session object
        final Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);
        /*
       * Register our extended SMTP transport. session.addProvider(p);
       */
        /*
       * Construct the message and send it.
       */
        final Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        msg.setSubject(subject);
        final String text = collect(in);
        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            final MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            final MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            final MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }
        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());
        /*
       * The simple way to send a message is this: Transport.send(msg); But
       * we're going to use some SMTP-specific features for demonstration
       * purposes so we need to manage the Transport object explicitly.
       */
        try (final SMTPTransport t = (SMTPTransport) session.getTransport(prot)) {
            if (auth)
                t.connect(mailhost, user, password);
            else
                t.connect();
            t.sendMessage(msg, msg.getAllRecipients());
            if (verbose)
                System.out.println("Response: " + t.getLastServerResponse());
        }
        System.out.println("\nMail was sent successfully.");
        /*
       * Save a copy of the message, if requested.
       */
        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                final URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();
                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }
            // Get record Folder. Create if it does not exist.
            final Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);
            final Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);
            System.out.println("Mail was recorded successfully.");
        }
    } catch (final MessagingException | IOException e) {
        /*
       * Handle SMTP-specific exceptions.
       */
        if (e instanceof SendFailedException) {
            MessagingException sfe = (MessagingException) e;
            if (sfe instanceof SMTPSendFailedException) {
                final SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                System.out.println("SMTP SEND FAILED:");
                if (verbose)
                    System.out.println(ssfe.toString());
                System.out.println("  Command: " + ssfe.getCommand());
                System.out.println("  RetCode: " + ssfe.getReturnCode());
                System.out.println("  Response: " + ssfe.getMessage());
            } else {
                if (verbose)
                    System.out.println("Send failed: " + sfe.toString());
            }
            Exception ne;
            while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                sfe = (MessagingException) ne;
                if (sfe instanceof SMTPAddressFailedException) {
                    final SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                    System.out.println("ADDRESS FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else if (sfe instanceof SMTPAddressSucceededException) {
                    System.out.println("ADDRESS SUCCEEDED:");
                    final SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                }
            }
        } else {
            System.out.println("Got Exception: " + e);
            if (verbose)
                e.printStackTrace();
        }
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) URLName(javax.mail.URLName) Store(javax.mail.Store) Properties(java.util.Properties) Folder(javax.mail.Folder) SMTPSendFailedException(com.sun.mail.smtp.SMTPSendFailedException) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) SMTPSendFailedException(com.sun.mail.smtp.SMTPSendFailedException) SendFailedException(javax.mail.SendFailedException) InputStreamReader(java.io.InputStreamReader) MessagingException(javax.mail.MessagingException) SMTPAddressFailedException(com.sun.mail.smtp.SMTPAddressFailedException) IOException(java.io.IOException) SMTPAddressSucceededException(com.sun.mail.smtp.SMTPAddressSucceededException) Date(java.util.Date) SMTPSendFailedException(com.sun.mail.smtp.SMTPSendFailedException) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) SMTPAddressFailedException(com.sun.mail.smtp.SMTPAddressFailedException) SMTPAddressSucceededException(com.sun.mail.smtp.SMTPAddressSucceededException) SendFailedException(javax.mail.SendFailedException) SMTPTransport(com.sun.mail.smtp.SMTPTransport) BufferedReader(java.io.BufferedReader) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Example 3 with SMTPAddressSucceededException

use of com.sun.mail.smtp.SMTPAddressSucceededException in project balcaovirtual by trf2-jus-br.

the class SMTPTransport method rcptTo.

/**
 * Sends each address to the SMTP host using the <code>RCPT TO:</code> command
 * and copies the address either into the validSentAddr or invalidAddr arrays.
 * Sets the <code>sendFailed</code> flag to true if any addresses failed.
 *
 * @since JavaMail 1.4.1
 */
/*
	 * success/failure/error possibilities from the RCPT command from rfc821,
	 * section 4.3 S: 250, 251 F: 550, 551, 552, 553, 450, 451, 452 E: 500, 501,
	 * 503, 421
	 * 
	 * and how we map the above error/failure conditions to valid/invalid address
	 * vectors that are reported in the thrown exception: invalid addr: 550, 501,
	 * 503, 551, 553 valid addr: 552 (quota), 450, 451, 452 (quota), 421 (srvr
	 * abort)
	 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void rcptTo() throws MessagingException {
    Vector valid = new Vector();
    Vector validUnsent = new Vector();
    Vector invalid = new Vector();
    int retCode = -1;
    MessagingException mex = null;
    boolean sendFailed = false;
    MessagingException sfex = null;
    validSentAddr = validUnsentAddr = invalidAddr = null;
    boolean sendPartial = false;
    if (message instanceof SMTPMessage)
        sendPartial = ((SMTPMessage) message).getSendPartial();
    if (!sendPartial) {
        String sp = session.getProperty("mail." + name + ".sendpartial");
        sendPartial = sp != null && sp.equalsIgnoreCase("true");
    }
    if (debug && sendPartial)
        out.println("DEBUG SMTP: sendPartial set");
    boolean dsn = false;
    String notify = null;
    if (supportsExtension("DSN")) {
        // Nato: notify = ((SMTPMessage) message).getDSNNotify();
        if (notify == null)
            notify = session.getProperty("mail." + name + ".dsn.notify");
        if (notify != null)
            dsn = true;
    }
    // try the addresses one at a time
    for (int i = 0; i < addresses.length; i++) {
        sfex = null;
        InternetAddress ia = (InternetAddress) addresses[i];
        String cmd = "RCPT TO:" + normalizeAddress(ia.getAddress());
        if (dsn)
            cmd += " NOTIFY=" + notify;
        // send the addresses to the SMTP server
        sendCommand(cmd);
        // check the server's response for address validity
        retCode = readServerResponse();
        switch(retCode) {
            case 250:
            case 251:
                valid.addElement(ia);
                if (!reportSuccess)
                    break;
                // user wants exception even when successful, including
                // details of the return code
                // create and chain the exception
                sfex = new SMTPAddressSucceededException(ia, cmd, retCode, lastServerResponse);
                if (mex == null)
                    mex = sfex;
                else
                    mex.setNextException(sfex);
                break;
            case 550:
            case 553:
            case 503:
            case 551:
            case 501:
                // given address is invalid
                if (!sendPartial)
                    sendFailed = true;
                invalid.addElement(ia);
                // create and chain the exception
                sfex = new SMTPAddressFailedException(ia, cmd, retCode, lastServerResponse);
                if (mex == null)
                    mex = sfex;
                else
                    mex.setNextException(sfex);
                break;
            case 552:
            case 450:
            case 451:
            case 452:
                // given address is valid
                if (!sendPartial)
                    sendFailed = true;
                validUnsent.addElement(ia);
                // create and chain the exception
                sfex = new SMTPAddressFailedException(ia, cmd, retCode, lastServerResponse);
                if (mex == null)
                    mex = sfex;
                else
                    mex.setNextException(sfex);
                break;
            default:
                // handle remaining 4xy & 5xy codes
                if (retCode >= 400 && retCode <= 499) {
                    // assume address is valid, although we don't really know
                    validUnsent.addElement(ia);
                } else if (retCode >= 500 && retCode <= 599) {
                    // assume address is invalid, although we don't really know
                    invalid.addElement(ia);
                } else {
                    // completely unexpected response, just give up
                    if (debug)
                        out.println("DEBUG SMTP: got response code " + retCode + ", with response: " + lastServerResponse);
                    // else rset will nuke
                    String _lsr = lastServerResponse;
                    // it
                    int _lrc = lastReturnCode;
                    if (// hasn't already been closed
                    serverSocket != null)
                        issueCommand("RSET", 250);
                    // restore, for get
                    lastServerResponse = _lsr;
                    lastReturnCode = _lrc;
                    throw new SMTPAddressFailedException(ia, cmd, retCode, _lsr);
                }
                if (!sendPartial)
                    sendFailed = true;
                // create and chain the exception
                sfex = new SMTPAddressFailedException(ia, cmd, retCode, lastServerResponse);
                if (mex == null)
                    mex = sfex;
                else
                    mex.setNextException(sfex);
                break;
        }
    }
    // valid addresses, that's complete failure
    if (sendPartial && valid.size() == 0)
        sendFailed = true;
    // copy the vectors into appropriate arrays
    if (sendFailed) {
        // copy invalid addrs
        invalidAddr = new Address[invalid.size()];
        invalid.copyInto(invalidAddr);
        // copy all valid addresses to validUnsent, since something failed
        validUnsentAddr = new Address[valid.size() + validUnsent.size()];
        int i = 0;
        for (int j = 0; j < valid.size(); j++) validUnsentAddr[i++] = (Address) valid.elementAt(j);
        for (int j = 0; j < validUnsent.size(); j++) validUnsentAddr[i++] = (Address) validUnsent.elementAt(j);
    } else if (reportSuccess || (sendPartial && (invalid.size() > 0 || validUnsent.size() > 0))) {
        // we'll go on to send the message, but after sending we'll
        // throw an exception with this exception nested
        sendPartiallyFailed = true;
        exception = mex;
        // copy invalid addrs
        invalidAddr = new Address[invalid.size()];
        invalid.copyInto(invalidAddr);
        // copy valid unsent addresses to validUnsent
        validUnsentAddr = new Address[validUnsent.size()];
        validUnsent.copyInto(validUnsentAddr);
        // copy valid addresses to validSent
        validSentAddr = new Address[valid.size()];
        valid.copyInto(validSentAddr);
    } else {
        // all addresses pass
        validSentAddr = addresses;
    }
    // print out the debug info
    if (debug) {
        if (validSentAddr != null && validSentAddr.length > 0) {
            out.println("DEBUG SMTP: Verified Addresses");
            for (int l = 0; l < validSentAddr.length; l++) {
                out.println("DEBUG SMTP:   " + validSentAddr[l]);
            }
        }
        if (validUnsentAddr != null && validUnsentAddr.length > 0) {
            out.println("DEBUG SMTP: Valid Unsent Addresses");
            for (int j = 0; j < validUnsentAddr.length; j++) {
                out.println("DEBUG SMTP:   " + validUnsentAddr[j]);
            }
        }
        if (invalidAddr != null && invalidAddr.length > 0) {
            out.println("DEBUG SMTP: Invalid Addresses");
            for (int k = 0; k < invalidAddr.length; k++) {
                out.println("DEBUG SMTP:   " + invalidAddr[k]);
            }
        }
    }
    // throw the exception, fire TransportEvent.MESSAGE_NOT_DELIVERED event
    if (sendFailed) {
        if (debug)
            out.println("DEBUG SMTP: Sending failed " + "because of invalid destination addresses");
        notifyTransportListeners(TransportEvent.MESSAGE_NOT_DELIVERED, validSentAddr, validUnsentAddr, invalidAddr, this.message);
        // reset the connection so more sends are allowed
        // save, for get
        String lsr = lastServerResponse;
        int lrc = lastReturnCode;
        try {
            if (serverSocket != null)
                issueCommand("RSET", 250);
        } catch (MessagingException ex) {
            // if can't reset, best to close the connection
            try {
                close();
            } catch (MessagingException ex2) {
                // thrown by close()--ignore, will close() later anyway
                if (debug)
                    ex2.printStackTrace(out);
            }
        } finally {
            // restore
            lastServerResponse = lsr;
            lastReturnCode = lrc;
        }
        throw new SendFailedException("Invalid Addresses", mex, validSentAddr, validUnsentAddr, invalidAddr);
    }
}
Also used : SMTPMessage(com.sun.mail.smtp.SMTPMessage) SMTPSendFailedException(com.sun.mail.smtp.SMTPSendFailedException) SMTPAddressFailedException(com.sun.mail.smtp.SMTPAddressFailedException) SMTPAddressSucceededException(com.sun.mail.smtp.SMTPAddressSucceededException)

Aggregations

SMTPAddressFailedException (com.sun.mail.smtp.SMTPAddressFailedException)3 SMTPAddressSucceededException (com.sun.mail.smtp.SMTPAddressSucceededException)3 SMTPSendFailedException (com.sun.mail.smtp.SMTPSendFailedException)2 Date (java.util.Date)2 MessagingException (javax.mail.MessagingException)2 SendFailedException (javax.mail.SendFailedException)2 MimeMessage (javax.mail.internet.MimeMessage)2 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)1 CommonsLinkedHashMap (com.helger.commons.collection.impl.CommonsLinkedHashMap)1 ICommonsList (com.helger.commons.collection.impl.ICommonsList)1 ICommonsOrderedSet (com.helger.commons.collection.impl.ICommonsOrderedSet)1 ICommonsSet (com.helger.commons.collection.impl.ICommonsSet)1 IMutableEmailData (com.helger.smtp.data.IMutableEmailData)1 EmailDataTransportEvent (com.helger.smtp.listener.EmailDataTransportEvent)1 IEmailDataTransportListener (com.helger.smtp.listener.IEmailDataTransportListener)1 SMTPMessage (com.sun.mail.smtp.SMTPMessage)1 SMTPTransport (com.sun.mail.smtp.SMTPTransport)1 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1