Package org.apache.james.core

Examples of org.apache.james.core.MailImpl


    notifyQueManager();
  }
  protected void service(MimeMessage mimeMessage, Collection<MailWatcher> watchers)
      throws AddressException, MessagingException {
   
    MailImpl sourceMail = new MailImpl(mimeMessage);
    // Do I want to give the internal key, or the message's Message ID
    if (log.isDebugEnabled())
      log.debug(getClass().getSimpleName()+".service(): Remotely delivering mail " + sourceMail.getName());
   
    /*
     * We don't need to organize recipients and separate into unique mails.
     * The RemoteDelivery could handle a mail with multiple recipients and
     * target servers.
View Full Code Here


    {
      if( log.isDebugEnabled() )
        log.debug(getClass().getSimpleName()+" ("+getName()+").deliver(): Starting mail delivery. qi="+qi);
     
      // Get objects required from QuedItem
      MailImpl mail = (MailImpl) qi.getMail();
      MimeMessage message = mail.getMessage();
      // Get all recipients
      Collection<MailAddress> recipients = mail.getRecipients();
//      InternetAddress addr[] = new InternetAddress[recipients.size()];
//      int j = 0;
//      // funky ass look because you can't getElementAt() in a Collection
//     
//      for (Iterator i = recipients.iterator(); i.hasNext(); j++) {
//        MailAddress currentRcpt = (MailAddress) i.next();
//        addr[j] = currentRcpt.toInternetAddress();
//      }
      if( recipients.size() <= 0 )
      {
        if (log.isDebugEnabled())
          log.debug(getClass().getSimpleName()+" ("+getName()+").deliver(): No recipients specified... returning");
        return true;
      }
      Iterator<MailAddress> it = recipients.iterator();
      while (it.hasNext()) {
        rcpt = (MailAddress) it.next();
        if( !qi.recepientHasBeenHandled(rcpt) )
          break;
      }
      InternetAddress[] addr = new InternetAddress[]{rcpt.toInternetAddress()};
     
      // If recipient is null, we could not handle this email
      if (rcpt == null)
      {
        log.error(getClass().getSimpleName()+" ("+getName()+").deliver(): Could not find unhandled recipient.");
        return false;
      }
      String host = rcpt.getHost();
      // Lookup the possible targets
      // Figure out which servers to try to send to. This collection
      // will hold all the possible target servers
      Collection<URLName> targetServers = null;
      // theoretically it is possible to not hav eone that hasn't been
      // handled
      // however that's only if something has gone really wrong.
      try {
        // targetServers = MXLookup.urlsForHost(host); // farking
        // unreliable jndi bs
        targetServers = getMXRecordsForHost(host);
      } catch (Exception e) {
        log.error(getClass().getSimpleName()+" ("+getName()+" ).deliver(): Could not get MX for "+host+".",e);
      }
      if (targetServers == null || targetServers.size() == 0) {
        log.warn(getClass().getSimpleName()+" ("+getName()+").deliver(): No mail server found for: " + host);
        StringBuffer exceptionBuffer = new StringBuffer(128)
        .append(
            "I found no MX record entries for the hostname ")
            .append(host)
            .append(
                ".  I cannot determine where to send this message.");
        return failMessage(qi, rcpt, new MessagingException(
            exceptionBuffer.toString()), true);
      } else if (log.isTraceEnabled()) {
        log.trace(getClass().getSimpleName()+" ("+getName()+").deliver(): "+ targetServers.size() + " servers found for "+ host+".");
      }
      MessagingException lastError = null;
      Iterator<URLName> i = targetServers.iterator();
      while (i.hasNext()) {
        try {
          URLName outgoingMailServer = (URLName) i.next();
          StringBuffer logMessageBuffer = null;
          if( log.isDebugEnabled() )
          {
            logMessageBuffer = new StringBuffer(256)
              .append(getClass().getSimpleName())
              .append(" (")
              .append(getName())
              .append(").deliver(): ")
              .append("Attempting delivery of ")
              .append(mail.getName())
              .append(" to host ")
              .append(outgoingMailServer.toString())
              .append(" to addresses ")
              .append(Arrays.asList(addr));
            log.debug(logMessageBuffer.toString());
          }
          Properties props = session.getProperties();
          if (mail.getSender() == null) {
            props.put("mail.smtp.from", "<>");
          } else {
            String sender = mail.getSender().toString();
            props.put("mail.smtp.from", sender);
          }
          // Many of these properties are only in later JavaMail
          // versions
          // "mail.smtp.ehlo" //default true
          // "mail.smtp.auth" //default false
          // "mail.smtp.dsn.ret" //default to nothing... appended
          // as
          // RET= after MAIL FROM line.
          // "mail.smtp.dsn.notify" //default to
          // nothing...appended as
          // NOTIFY= after RCPT TO line.
          Transport transport = null;
          try {
            transport = session.getTransport(outgoingMailServer);
            try {
              transport.connect();
            } catch (MessagingException me) {
              log.error(getClass().getSimpleName()+" ("+getName()+").deliver(): Connection failed.",me);
              // Any error on connect should cause the mailet
              // to
              // attempt
              // to connect to the next SMTP server associated
              // with this MX record,
              // assuming the number of retries hasn't been
              // exceeded.
              if (failMessage(qi, rcpt, me, false)) {
                return true;
              } else {
                continue;
              }
            }
            transport.sendMessage(message, addr);
            // log.debug("message sent to " +addr);
            /*TODO: catch failures that should result
             * in failure with no retries
             } catch (SendFailedException sfe){
              qi.failForRecipient(que, );
             */
          } finally {
            if (transport != null) {
              transport.close();
              transport = null;
            }
          }
          logMessageBuffer = new StringBuffer(256)
            .append("Mail (")
            .append(mail.getName())
            .append(") sent successfully to ")
            .append(outgoingMailServer);
          log.debug(getClass().getSimpleName()+" ("+getName()+").deliver(): "+logMessageBuffer.toString());
          qi.succeededForRecipient(que, rcpt);
          return true;
        } catch (MessagingException me) {
          log.error(getClass().getSimpleName()+" ("+getName()+").deliver(): ", me);
          // MessagingException are horribly difficult to figure
          // out
          // what actually happened.
          StringBuffer exceptionBuffer = new StringBuffer(256)
            .append("Exception delivering message (")
            .append(mail.getName())
            .append(") - ")
            .append(me.getMessage());
          log.warn(exceptionBuffer.toString());
          if ((me.getNextException() != null)
              && (me.getNextException() instanceof java.io.IOException)) {
View Full Code Here

   */
  private boolean failMessage(QuedItem qi, MailAddress recepient,
      MessagingException ex, boolean permanent) {
    log.debug(getClass().getSimpleName()+" ("+getName()+").failMessage(): Method called. qi="+qi);
    // weird printy bits inherited from JAMES
    MailImpl mail = (MailImpl) qi.getMail();
    StringWriter sout = new StringWriter();
    PrintWriter out = new PrintWriter(sout, true);
    if (permanent) {
      out.print("Permanent");
    } else {
      out.print("Temporary");
    }
    StringBuffer logBuffer = new StringBuffer(64)
      .append(getClass().getSimpleName())
      .append(" (")
      .append(getName())
      .append(").failMessage(): ")
      .append(
        " exception delivering mail (").append(mail.getName()).append(
        ": ");
    out.print(logBuffer.toString());
    ex.printStackTrace(out);
    if (log.isWarnEnabled()) {
      log.warn(sout.toString());
    }
    // //////////////
    // / It is important to note that deliver will pass us a mail with a
    // modified
    // / list of recepients non permanent ones will only have valid
    // recepients left
    // /
    if (!permanent) {
      if (!mail.getState().equals(Mail.ERROR)) {
        mail.setState(Mail.ERROR);
        mail.setErrorMessage("0");
        mail.setLastUpdated(new Date());
      }
      if (qi.retryable(recepient)) {
        if (log.isDebugEnabled()) {
          logBuffer = new StringBuffer(128)
            .append(getClass().getSimpleName()+" ("+getName()+").failMessage(): ")
            .append("Storing message ")
            .append(mail.getName())
            .append(" into que after ")
//            .append(qi.getNumAttempts())
            .append(" attempts")
          ;
          log.debug(logBuffer.toString());
        }
        qi.retry(que, recepient);
        //mail.setErrorMessage(qi.getNumAttempts() + "");
        mail.setLastUpdated(new Date());
        return false;
      } else {
        if (log.isDebugEnabled()) {
          logBuffer = new StringBuffer(128)
            .append(getClass().getSimpleName()+" ("+getName()+").failMessage(): ")
            .append("Bouncing message ")
            .append(mail.getName())
            .append(" after ")
//            .append(qi.getNumAttempts())
            .append(" attempts")
          ;
          log.debug(logBuffer.toString());
View Full Code Here

    protected MailImpl duplicate(MailImpl aMail) throws MessagingException {
        // duplicates the Mail object, to be able to modify the new mail
        // keeping
        // the original untouched
        MailImpl newMail = (MailImpl) aMail.duplicate(newName(aMail));
        // We don't need to use the original Remote Address and Host,
        // and doing so would likely cause a loop with spam detecting
        // matchers.
        try {
            newMail.setRemoteAddr(java.net.InetAddress.getLocalHost()
                    .getHostAddress());
            newMail.setRemoteHost(java.net.InetAddress.getLocalHost()
                    .getHostName());
        } catch (java.net.UnknownHostException _) {
            newMail.setRemoteAddr("127.0.0.1");
            newMail.setRemoteHost("localhost");
        }
        return newMail;
    }
View Full Code Here

     *
     * @throws MessagingException
     */
    public void testExecuteActionKeep() throws MessagingException {
        boolean isTestPassed = false;
        Mail aMail = new MailImpl();
        aMail.setRecipients(Arrays.asList(new MailAddress[] { new MailAddress(
                "a", "a.com") }));
        MimeMessage mimeMessage = new MimeMessage(Session
                .getDefaultInstance(new Properties()));
        mimeMessage.setText("TEST");
        aMail.setMessage(mimeMessage);
        MailetContext aMailetContext = new MockMailetContext();
        Action action = new ActionKeep();
        try {
            ActionDispatcher.getInstance().execute(action, aMail,
                    aMailetContext);
View Full Code Here

    /**
     * Test execute of ActionAbsent. Should throw a NoSuchMethodException.
     */
    public void testExecuteActionAbsent() {
        boolean isTestPassed = false;
        Mail aMail = new MailImpl();
        MailetContext aMailetContext = new MockMailetContext();
        Action action = new ActionAbsent();
        try {
            ActionDispatcher.getInstance().execute(action, aMail,
                    aMailetContext);
View Full Code Here

     * @return
     * @throws MessagingException
     * @throws JMSException
     */
    protected final Mail createMail(Message message) throws MessagingException, JMSException {
        MailImpl mail = new MailImpl();
        populateMail(message, mail);
        populateMailMimeMessage(message, mail);

        return mail;
    }
View Full Code Here

    protected Mail createMail(MimeMessage message, MailAddress recipient)
        throws MessagingException, UnknownHostException
    {
        Collection<MailAddress> recipients = new ArrayList<MailAddress>(1);
        recipients.add(recipient);
        MailImpl mail =
            new MailImpl(getServer().getId(), getSender(), recipients, message);
        // Ensure the mail is created with non-null remote host name and address,
        // otherwise the Mailet chain may go splat!
        if (getRemoteAddress() == null || getRemoteHostName() == null)
        {
            mail.setRemoteAddr("127.0.0.1");
            mail.setRemoteHost("localhost");
            setDefaultRemoteAddress(true);         
            logStatusInfo("Remote address could not be determined. Using localhost/127.0.0.1");            
        }
        else
        {
            mail.setRemoteAddr(getRemoteAddress());
            mail.setRemoteHost(getRemoteHostName());
            setDefaultRemoteAddress(false);           
        }

        logMailCreation(mail);
        return mail;
View Full Code Here

            if (line.length == 3 && line[0] == 46) {
                out.flush();
                out.close();
               
                List recipientCollection = (List) session.getState().get(SMTPSession.RCPT_LIST);
                MailImpl mail =
                    new MailImpl(mailServer.getId(),
                                 (MailAddress) session.getState().get(SMTPSession.SENDER),
                                 recipientCollection);
               
                // store mail in the session so we can be sure it get disposed later
                session.getState().put(SMTPConstants.MAIL, mail);
               
                MimeMessageCopyOnWriteProxy mimeMessageCopyOnWriteProxy = null;
                try {
                    mimeMessageCopyOnWriteProxy = new MimeMessageCopyOnWriteProxy(mmiss);
                    mail.setMessage(mimeMessageCopyOnWriteProxy);
                   
                    deliverMail(session, mail);
                   
                    session.popLineHandler();
                          
View Full Code Here

            // address
            if (log.isInfoEnabled())
                log.info("Processing a bounce request for a message with a reverse path of " + mail.getSender().toString());
        }

        MailImpl reply = rawBounce(mail, message);
        // Change the sender...
        reply.getMessage().setFrom(bouncer.toInternetAddress());
        reply.getMessage().saveChanges();
        // Send it off ... with null reverse-path
        reply.setSender(null);
        sendMail(reply);
        LifecycleUtil.dispose(reply);
    }
View Full Code Here

TOP

Related Classes of org.apache.james.core.MailImpl

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.