Example usage for javax.mail Address toString

List of usage examples for javax.mail Address toString

Introduction

In this page you can find the example usage for javax.mail Address toString.

Prototype

@Override
public abstract String toString();

Source Link

Document

Return a String representation of this address object.

Usage

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

private Sequence getMessageListAsXML(Sequence[] args, Sequence contextSequence) throws XPathException {
    Message[] msgList;/*  w  ww . j a va 2  s . co m*/
    Sequence ret = Sequence.EMPTY_SEQUENCE;

    // was a msgList handle specified?
    if (args[0].isEmpty()) {
        throw (new XPathException(this, "Message List handle not specified"));
    }

    // get the MessageList
    long msgListHandle = ((IntegerValue) args[0].itemAt(0)).getLong();
    msgList = MailModule.retrieveMessageList(context, msgListHandle);
    if (msgList == null) {
        throw (new XPathException(this, "Invalid Message List handle specified"));
    }

    if (msgList.length > 0) {

        boolean includeHeaders = args[1].effectiveBooleanValue();

        MemTreeBuilder builder = context.getDocumentBuilder();

        builder.startDocument();
        builder.startElement(new QName("messages", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        builder.addAttribute(new QName("count", null, null), String.valueOf(msgList.length));

        try {
            for (int i = 0; i < msgList.length; i++) {
                Message message = msgList[i];

                builder.startElement(new QName("message", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);

                builder.addAttribute(new QName("number", null, null),
                        String.valueOf(message.getMessageNumber()));

                // Sent Date
                if (message.getSentDate() != null) {
                    builder.startElement(new QName("sent", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                    builder.characters(formatDate(message.getSentDate()));
                    builder.endElement();
                }

                // Received Date
                if (message.getReceivedDate() != null) {
                    builder.startElement(new QName("received", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                            null);
                    builder.characters(formatDate(message.getReceivedDate()));
                    builder.endElement();
                }

                // From
                if (message.getFrom() != null) {
                    builder.startElement(new QName("from", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                    builder.characters(message.getFrom()[0].toString());
                    builder.endElement();
                }

                // Recipients
                builder.startElement(new QName("recipients", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                        null);
                // To Recipients
                Address[] toAddresses = message.getRecipients(Message.RecipientType.TO);
                if (toAddresses != null) {
                    for (Address to : toAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "to");
                        builder.characters(to.toString());
                        builder.endElement();
                    }
                }

                // cc Recipients
                Address[] ccAddresses = message.getRecipients(Message.RecipientType.CC);
                if (ccAddresses != null) {
                    for (Address ccAddress : ccAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "cc");
                        builder.characters(ccAddress.toString());
                        builder.endElement();
                    }
                }

                // bcc Recipients
                Address[] bccAddresses = message.getRecipients(Message.RecipientType.BCC);
                if (bccAddresses != null) {
                    for (Address bccAddress : bccAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "bcc");
                        builder.characters(bccAddress.toString());
                        builder.endElement();
                    }
                }
                builder.endElement();

                // Flags

                Flags flags = message.getFlags();
                Flags.Flag[] systemFlags = flags.getSystemFlags();
                String[] userFlags = flags.getUserFlags();

                if (systemFlags.length > 0 || userFlags.length > 0) {
                    builder.startElement(new QName("flags", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);

                    for (Flags.Flag systemFlag : systemFlags) {
                        if (systemFlag == Flags.Flag.ANSWERED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "answered");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.DELETED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "deleted");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.DRAFT) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "draft");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.FLAGGED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "flagged");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.RECENT) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "recent");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.SEEN) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "seen");
                            builder.endElement();
                        }
                    }

                    for (String userFlag : userFlags) {
                        builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                null);
                        builder.addAttribute(new QName("type", null, null), "user");
                        builder.addAttribute(new QName("value", null, null), userFlag);
                        builder.endElement();
                    }

                    builder.endElement();
                }

                // Headers

                if (includeHeaders) {
                    Enumeration headers = message.getAllHeaders();

                    if (headers.hasMoreElements()) {
                        builder.startElement(new QName("headers", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                null);

                        while (headers.hasMoreElements()) {
                            Header header = (Header) headers.nextElement();

                            builder.startElement(
                                    new QName("header", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                            builder.addAttribute(new QName("name", null, null), header.getName());
                            builder.addAttribute(new QName("value", null, null), header.getValue());
                            builder.endElement();
                        }

                        builder.endElement();
                    }
                }

                // Subject
                builder.startElement(new QName("subject", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                builder.characters(message.getSubject());
                builder.endElement();

                builder.endElement();
            }
        } catch (MessagingException me) {
            throw (new XPathException(this, "Failed to retrieve messages from list", me));
        }

        builder.endElement();

        ret = (NodeValue) builder.getDocument().getDocumentElement();
    }

    return (ret);
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

private InternetAddress getRawEmailFromAddress(Address address) throws AddressException {
    if (address == null) {
        throw new AddressException("Address cannot be null");
    }//from  ww w  . ja  v a 2 s . com
    InternetAddress fromAddress = new InternetAddress(address.toString());
    String fromPlainAddress = fromAddress.getAddress();
    return new InternetAddress(fromPlainAddress);
}

From source file:org.apache.manifoldcf.crawler.connectors.email.EmailConnector.java

/** Process a set of documents.
* This is the method that should cause each document to be fetched, processed, and the results either added
* to the queue of documents for the current job, and/or entered into the incremental ingestion manager.
* The document specification allows this class to filter what is done based on the job.
* The connector will be connected before this method can be called.
*@param documentIdentifiers is the set of document identifiers to process.
*@param statuses are the currently-stored document versions for each document in the set of document identifiers
* passed in above.// w  w w  .  j av  a  2 s  .  c  o  m
*@param activities is the interface this method should use to queue up new document references
* and ingest documents.
*@param jobMode is an integer describing how the job is being run, whether continuous or once-only.
*@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one.
*/
@Override
public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec,
        IProcessActivity activities, int jobMode, boolean usesDefaultAuthority)
        throws ManifoldCFException, ServiceInterruption {

    List<String> requiredMetadata = new ArrayList<String>();
    for (int i = 0; i < spec.getChildCount(); i++) {
        SpecificationNode sn = spec.getChild(i);
        if (sn.getType().equals(EmailConfig.NODE_METADATA)) {
            String metadataAttribute = sn.getAttributeValue(EmailConfig.ATTRIBUTE_NAME);
            requiredMetadata.add(metadataAttribute);
        }
    }

    // Keep a cached set of open folders
    Map<String, Folder> openFolders = new HashMap<String, Folder>();
    try {

        for (String documentIdentifier : documentIdentifiers) {
            String versionString = "_" + urlTemplate; // NOT empty; we need to make ManifoldCF understand that this is a document that never will change.

            // Check if we need to index
            if (!activities.checkDocumentNeedsReindexing(documentIdentifier, versionString))
                continue;

            String compositeID = documentIdentifier;
            String version = versionString;
            String folderName = extractFolderNameFromDocumentIdentifier(compositeID);
            String id = extractEmailIDFromDocumentIdentifier(compositeID);

            String errorCode = null;
            String errorDesc = null;
            Long fileLengthLong = null;
            long startTime = System.currentTimeMillis();
            try {
                try {
                    Folder folder = openFolders.get(folderName);
                    if (folder == null) {
                        getSession();
                        OpenFolderThread oft = new OpenFolderThread(session, folderName);
                        oft.start();
                        folder = oft.finishUp();
                        openFolders.put(folderName, folder);
                    }

                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug("Email: Processing document identifier '" + compositeID + "'");
                    SearchTerm messageIDTerm = new MessageIDTerm(id);

                    getSession();
                    SearchMessagesThread smt = new SearchMessagesThread(session, folder, messageIDTerm);
                    smt.start();
                    Message[] message = smt.finishUp();

                    String msgURL = makeDocumentURI(urlTemplate, folderName, id);

                    Message msg = null;
                    for (Message msg2 : message) {
                        msg = msg2;
                    }
                    if (msg == null) {
                        // email was not found
                        activities.deleteDocument(id);
                        continue;
                    }

                    if (!activities.checkURLIndexable(msgURL)) {
                        errorCode = activities.EXCLUDED_URL;
                        errorDesc = "Excluded because of URL ('" + msgURL + "')";
                        activities.noDocument(id, version);
                        continue;
                    }

                    long fileLength = msg.getSize();
                    if (!activities.checkLengthIndexable(fileLength)) {
                        errorCode = activities.EXCLUDED_LENGTH;
                        errorDesc = "Excluded because of length (" + fileLength + ")";
                        activities.noDocument(id, version);
                        continue;
                    }

                    Date sentDate = msg.getSentDate();
                    if (!activities.checkDateIndexable(sentDate)) {
                        errorCode = activities.EXCLUDED_DATE;
                        errorDesc = "Excluded because of date (" + sentDate + ")";
                        activities.noDocument(id, version);
                        continue;
                    }

                    String mimeType = "text/plain";
                    if (!activities.checkMimeTypeIndexable(mimeType)) {
                        errorCode = activities.EXCLUDED_DATE;
                        errorDesc = "Excluded because of mime type ('" + mimeType + "')";
                        activities.noDocument(id, version);
                        continue;
                    }

                    RepositoryDocument rd = new RepositoryDocument();
                    rd.setFileName(msg.getFileName());
                    rd.setMimeType(mimeType);
                    rd.setCreatedDate(sentDate);
                    rd.setModifiedDate(sentDate);

                    String subject = StringUtils.EMPTY;
                    for (String metadata : requiredMetadata) {
                        if (metadata.toLowerCase().equals(EmailConfig.EMAIL_TO)) {
                            Address[] to = msg.getRecipients(Message.RecipientType.TO);
                            String[] toStr = new String[to.length];
                            int j = 0;
                            for (Address address : to) {
                                toStr[j] = address.toString();
                            }
                            rd.addField(EmailConfig.EMAIL_TO, toStr);
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_FROM)) {
                            Address[] from = msg.getFrom();
                            String[] fromStr = new String[from.length];
                            int j = 0;
                            for (Address address : from) {
                                fromStr[j] = address.toString();
                            }
                            rd.addField(EmailConfig.EMAIL_TO, fromStr);

                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_SUBJECT)) {
                            subject = msg.getSubject();
                            rd.addField(EmailConfig.EMAIL_SUBJECT, subject);
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_BODY)) {
                            Multipart mp = (Multipart) msg.getContent();
                            for (int k = 0, n = mp.getCount(); k < n; k++) {
                                Part part = mp.getBodyPart(k);
                                String disposition = part.getDisposition();
                                if ((disposition == null)) {
                                    MimeBodyPart mbp = (MimeBodyPart) part;
                                    if (mbp.isMimeType(EmailConfig.MIMETYPE_TEXT_PLAIN)) {
                                        rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString());
                                    } else if (mbp.isMimeType(EmailConfig.MIMETYPE_HTML)) {
                                        rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); //handle html accordingly. Returns content with html tags
                                    }
                                }
                            }
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_DATE)) {
                            rd.addField(EmailConfig.EMAIL_DATE, sentDate.toString());
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_ENCODING)) {
                            Multipart mp = (Multipart) msg.getContent();
                            if (mp != null) {
                                String[] encoding = new String[mp.getCount()];
                                for (int k = 0, n = mp.getCount(); k < n; k++) {
                                    Part part = mp.getBodyPart(k);
                                    String disposition = part.getDisposition();
                                    if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)
                                            || (disposition.equals(Part.INLINE))))) {
                                        encoding[k] = part.getFileName().split("\\?")[1];

                                    }
                                }
                                rd.addField(EmailConfig.ENCODING_FIELD, encoding);
                            }
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_MIMETYPE)) {
                            Multipart mp = (Multipart) msg.getContent();
                            String[] MIMEType = new String[mp.getCount()];
                            for (int k = 0, n = mp.getCount(); k < n; k++) {
                                Part part = mp.getBodyPart(k);
                                String disposition = part.getDisposition();
                                if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)
                                        || (disposition.equals(Part.INLINE))))) {
                                    MIMEType[k] = part.getContentType();

                                }
                            }
                            rd.addField(EmailConfig.MIMETYPE_FIELD, MIMEType);
                        }
                    }

                    InputStream is = msg.getInputStream();
                    try {
                        rd.setBinary(is, fileLength);
                        activities.ingestDocumentWithException(id, version, msgURL, rd);
                        errorCode = "OK";
                        fileLengthLong = new Long(fileLength);
                    } finally {
                        is.close();
                    }
                } catch (InterruptedException e) {
                    throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED);
                } catch (MessagingException e) {
                    errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
                    errorDesc = e.getMessage();
                    handleMessagingException(e, "processing email");
                } catch (IOException e) {
                    errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
                    errorDesc = e.getMessage();
                    handleIOException(e, "processing email");
                    throw new ManifoldCFException(e.getMessage(), e);
                }
            } catch (ManifoldCFException e) {
                if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)
                    errorCode = null;
                throw e;
            } finally {
                if (errorCode != null)
                    activities.recordActivity(new Long(startTime), EmailConfig.ACTIVITY_FETCH, fileLengthLong,
                            documentIdentifier, errorCode, errorDesc, null);
            }
        }
    } finally {
        for (Folder f : openFolders.values()) {
            try {
                CloseFolderThread cft = new CloseFolderThread(session, f);
                cft.start();
                cft.finishUp();
            } catch (InterruptedException e) {
                throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED);
            } catch (MessagingException e) {
                handleMessagingException(e, "closing folders");
            }
        }
    }

}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * IN USE/*from  w w w .ja v a 2  s .  c o m*/
 * 
 * @param request
 * @return
 * @throws Exception
 */
public GetMessageDetailResponseType getMessageDetail(GetMessageDetailRequestType request) throws Exception {
    System.out.println("===> DMD.getMessageDetail: Looking for msgId=" + request.getMessageId());
    System.out.println("===> DMD.getMessageDetail: request patientId=" + request.getPatientId());
    System.out.println("===> DMD.getMessageDetail: request    userId=" + request.getUserId());

    GetMessageDetailResponseType response = new GetMessageDetailResponseType();

    IMAPFolder msgFolder = null;
    IMAPSSLStore sslStore = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    //------------------------------------------------------------------
    // When patientId is given, access must be from EMR Inbox.
    //      Get email msgs from Patient's email account.
    // Else
    //      Get email msgs from logged in user's email account.
    //------------------------------------------------------------------
    ContactDTO contact = null;
    String userType = "";
    String[] access = new String[2];

    if (!CommonUtil.strNullorEmpty(request.getPatientId())) {
        contact = contactDAO.findContact("uid=" + request.getPatientId()).get(0);
        userType = ITEM_ID_PATIENT;

    } else {
        contact = contactDAO.findContact("uid=" + request.getUserId()).get(0);
        userType = ITEM_ID_PROVIDER;
    }
    access = retrieveMailAccess(contact.getCommonName(), contact.getUid());

    try {
        session = Session.getInstance(new Properties());
        URLName urlName = new URLName(mailUrl);

        //--------------------------------------------
        //Get the sslStore and connect
        //--------------------------------------------
        sslStore = new IMAPSSLStore(session, urlName);
        sslStore.connect(host, access[0], access[1]);

        //--------------------------------------------
        // Set the originating folder.
        // Default to INBOX if not given.
        // Get and open the IMAP folder
        //--------------------------------------------
        String folderName = null;
        if (CommonUtil.strNullorEmpty(request.getLocation())) {
            folderName = "INBOX";
        } else {
            folderName = mapKmrLocationToImapFolder(request.getLocation(), this.host);
        }

        msgFolder = (IMAPFolder) sslStore.getFolder(folderName);
        msgFolder.open(Folder.READ_ONLY);

        //--------------------------------------------
        // Find the message by the given Message-ID
        //--------------------------------------------
        Message msg = this.findMsgByMessageId(msgFolder, request.getMessageId());

        if (msg == null) {
            String errmsg = "Msg NOT FOUND for Message-ID=" + request.getMessageId();
            System.out.println("===> getMessageDetail: " + errmsg);

            response.setSuccessStatus(false);
            response.setStatusMessage(errmsg);

        } else {
            //this.printMsgIdSubject(msg); //DBG printout
            System.out.println("===> getMessageDetail: Msg FOUND for Message-ID=" + request.getMessageId());

            //---------------------------------------------------
            // Extract "PATIENTID=" from body if present, so that
            // user does not see it.
            //---------------------------------------------------
            String content = fetchMsgContent(msg);

            if (content.startsWith("PATIENTID=")) {
                Scanner scanner = new Scanner(content);
                boolean first = true;
                StringBuilder sb = new StringBuilder();
                while (scanner.hasNextLine()) {
                    if (first) {
                        String[] parts = scanner.nextLine().split("=");
                        response.setPatientId(parts[1]);
                        first = false;
                    } else {
                        sb.append(scanner.nextLine());
                    }

                }
                response.getMessageDetail().add(sb.toString());
            } else {
                response.getMessageDetail().add(content);
            }

            // Adding patientId coming from the message header.
            //            if (msg.getHeader("X-PATIENTID") != null &&
            //                msg.getHeader("X-PATIENTID").length > 0) {
            //
            //                response.setPatientId(msg.getHeader("X-PATIENT_ID")[0]);
            //            }

            if (msg.getRecipients(Message.RecipientType.TO) != null) {
                for (Address a : msg.getRecipients(Message.RecipientType.TO)) {
                    String contactId = getContactIdFromEmail(a.toString());
                    response.getSentTo().add(contactId);

                    //System.out.println("DisplayMailDataHandler: TO="+ a.toString() +" ldap.cn="+ contactId);
                }
            }

            if (msg.getRecipients(Message.RecipientType.CC) != null) {
                for (Address a : msg.getRecipients(Message.RecipientType.CC)) {
                    String contactId = getContactIdFromEmail(a.toString());
                    response.getCCTo().add(contactId);

                    //System.out.println("DisplayMailDataHandler: CC="+ a.toString() +" ldap.cn="+ contactId);
                }
            }

            if (msg.getRecipients(Message.RecipientType.BCC) != null) {
                for (Address a : msg.getRecipients(Message.RecipientType.BCC)) {
                    String contactId = getContactIdFromEmail(a.toString());
                    response.getBCCTo().add(contactId);

                    //System.out.println("DisplayMailDataHandler: BCC="+ a.toString() +" ldap.cn="+ contactId);
                }
            }
            response.setSuccessStatus(true);
            response.setStatusMessage("");
        }

    } catch (Exception e) {
        response.setSuccessStatus(false);
        response.setStatusMessage(
                "Error getting message detail for user: " + access[0] + "\n[EXCEPTION] " + e.toString());
        e.printStackTrace();

    } finally {
        if (msgFolder != null) {
            try {
                msgFolder.close(false);
            } catch (Exception e) {
            }
        }

        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (Exception e) {
            }
        }
    }

    return response;
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

/**
 * /*from  www . j  a  va 2s  .  c  om*/
 * @param bounceAdress must be a raw email, without anything else (no "bla bli <bla@bli.ch>" !)
 * @return
 */
private MimeMessage createMessage(Address bounceAdress) {
    String mailhost = WebappHelper.getMailConfig("mailhost");
    String mailhostTimeout = WebappHelper.getMailConfig("mailTimeout");
    boolean sslEnabled = Boolean.parseBoolean(WebappHelper.getMailConfig("sslEnabled"));
    boolean sslCheckCertificate = Boolean.parseBoolean(WebappHelper.getMailConfig("sslCheckCertificate"));

    Authenticator smtpAuth;
    if (WebappHelper.isMailHostAuthenticationEnabled()) {
        String smtpUser = WebappHelper.getMailConfig("smtpUser");
        String smtpPwd = WebappHelper.getMailConfig("smtpPwd");
        smtpAuth = new MailerSMTPAuthenticator(smtpUser, smtpPwd);
    } else {
        smtpAuth = null;
    }

    Properties p = new Properties();
    p.put("mail.smtp.from", bounceAdress.toString());
    p.put("mail.smtp.host", mailhost);
    p.put("mail.smtp.timeout", mailhostTimeout);
    p.put("mail.smtp.connectiontimeout", mailhostTimeout);
    p.put("mail.smtp.ssl.enable", sslEnabled);
    p.put("mail.smtp.ssl.checkserveridentity", sslCheckCertificate);
    Session mailSession;
    if (smtpAuth == null) {
        mailSession = javax.mail.Session.getInstance(p);
    } else {
        // use smtp authentication from configuration
        p.put("mail.smtp.auth", "true");
        mailSession = Session.getDefaultInstance(p, smtpAuth);
    }
    if (isLogDebugEnabled()) {
        // enable mail session debugging on console
        mailSession.setDebug(true);
    }
    return new MimeMessage(mailSession);
}

From source file:com.riq.MailHandlerServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)

        throws IOException {

    log.info("Inside MailServlet doPost");

    // TODO get path information to determine target Department for this email

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {//from ww w  .  ja  v a  2s  .c om

        MimeMessage msg = new MimeMessage(session, req.getInputStream());
        Address sender = msg.getFrom()[0];
        Address replyTo = msg.getReplyTo()[0];

        //      DEBUG
        //       log.info("Message Class: " + msg.getClass());
        //       log.info("Message Stream: " + msg.getInputStream());
        //       log.info("Message RawStream: " + msg.getRawInputStream());
        //       log.info("Message Flags: " + msg.getFlags());
        //       log.info("Message Content: " + msg.getContent().toString());
        //       log.info("Message ContentID: " + msg.getContentID());
        //       log.info("Message ContentMD: " + msg.getContentMD5());
        //       log.info("Message ContentType: " + msg.getContentType());
        //       log.info("Message Description: " + msg.getDescription());
        //       log.info("Message Disposition: " + msg.getDisposition());
        //       log.info("Message Encoding: " + msg.getEncoding());
        //       log.info("Message Filename: " + msg.getFileName());
        //       log.info("Message Line Count: " + msg.getLineCount());
        //       log.info("Message ID: " + msg.getMessageID());
        //       log.info("Message Number: " + msg.getMessageNumber());
        //       log.info("Message Size: " + msg.getSize());
        //       log.info("Message Subject: " + msg.getSubject());
        //       log.info("Message RawInputStream: " + msg.getRawInputStream().toString());
        //       log.info("Message ReplyTo: " + replyTo);
        //       log.info("Message Sender: " + sender.toString());
        //       log.info("Request URL TO: " +  getServletContext());      

        String alertMsgString = getText(msg);

        alertMsgString = alertMsgString.replaceAll("Begin forwarded message:", "");
        alertMsgString = alertMsgString.replaceAll("Forwarded message", "");
        alertMsgString = alertMsgString.replaceAll("Dispatch@co.morris.nj.us", "");
        alertMsgString = alertMsgString.replaceAll("Date:", "");
        alertMsgString = alertMsgString.replaceAll(">", "");
        alertMsgString = alertMsgString.replaceAll("::", "-");
        alertMsgString = alertMsgString.replaceAll("< ", "");
        alertMsgString = alertMsgString.replaceAll("----------", "");
        alertMsgString = alertMsgString.replaceAll("Subject:", "");
        alertMsgString = alertMsgString.replaceAll("To:", "");
        alertMsgString = alertMsgString.replaceAll("From:", "");

        //  Added to grab gmail confirmations
        //  alertMsgString = alertMsgString.substring(50, 300);

        try {

            String queryDept = "select from " + Department.class.getName() +
            // TODO: johnreilly workaround for getting allRecipients... 
            // " where dispatchId == '" + toAddressDigitsOnly + "' " + 
                    " where dispatchId == '2599' " + " && fromEmail == '" + sender + "' ";
            log.info("queryDept: " + queryDept);
            List<Department> depts = (List<Department>) pm.newQuery(queryDept).execute();

            if (depts.size() != 0) {

                for (Department d : depts) {

                    // need to filter further e.g. last two hours
                    String queryAlert = "select from " + Alert.class.getName() + " where deptId == "
                            + depts.get(0).getid() + " && messageId == '" + msg.getMessageID() + "' ";
                    log.info("queryAlert: " + queryAlert);
                    List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlert).execute();
                    log.info("queryAlert Result Qty: " + alerts.size());

                    if (alerts.size() == 0) {

                        riqGeocode(alertMsgString);

                        // geocode the address from the Alert
                        Map<String, String> geoResults = riqGeocode(alertMsgString);
                        log.info("lat print: " + geoResults.get("lat"));
                        log.info("lng print: " + geoResults.get("lng"));

                        // create the alert
                        Long deptId = depts.get(0).getid();
                        Long timeStamp = System.currentTimeMillis();
                        Alert a = new Alert(deptId, timeStamp, alertMsgString.trim(), sender.toString(),
                                "Active", "", geoResults.get("lat"), geoResults.get("lng"), msg.getMessageID());
                        pm.makePersistent(a);

                        // query to get id of this alert
                        String queryThisAlert = "select from " + Alert.class.getName() + " where deptId == "
                                + deptId + " " + " && timeStamp == " + timeStamp;
                        log.info("queryThisAlert: " + queryThisAlert);
                        List<Alert> thisAlert = (List<Alert>) pm.newQuery(queryThisAlert).execute();
                        log.info("queryCurrentAlert Result Qty: " + thisAlert.size());

                        // create Tracking records for "special" Locations
                        String querySpecialLocs = "select from " + Location.class.getName()
                                + " where special == 'yes' && deptId == " + deptId;
                        log.info("querySpecialLocs: " + querySpecialLocs);
                        List<Location> specialLocs = (List<Location>) pm.newQuery(querySpecialLocs).execute();
                        log.info("querySpecialLocs qty: " + specialLocs.size());

                        for (Location specL : specialLocs) {
                            Tracking tSL = new Tracking(deptId, thisAlert.get(0).getid(), specL.getid(),
                                    System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd
                                    "location", specL.getid(), null, "autoAddLocation");
                            pm.makePersistent(tSL);
                        }

                        // search Dept for Location where distant Members presumed not to be responding are set
                        String queryFarawayLocs = "select from " + Location.class.getName()
                                + " where vru == '2' && deptId == " + deptId;
                        log.info("querySpecialLocs: " + queryFarawayLocs);
                        List<Location> farawayLoc = (List<Location>) pm.newQuery(queryFarawayLocs).execute();
                        log.info("queryFarawayLocs qty: " + farawayLoc.size());

                        // create Tracking records for Members presumed not to be responder due to fresh ETA
                        String queryFarAwayResponders = "select from " + Member.class.getName()
                                + " where distGroup == '4' ";
                        log.info("queryFarAwayResponders: " + queryFarAwayResponders);
                        List<Member> farawayMembers = (List<Member>) pm.newQuery(queryFarAwayResponders)
                                .execute();
                        log.info("queryFarAwayResponders qty: " + farawayMembers.size());

                        if (farawayMembers.size() != 0) {
                            for (Member far : farawayMembers) {
                                Tracking tMFAR = new Tracking(deptId, thisAlert.get(0).getid(),
                                        farawayLoc.get(0).getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd
                                        "farawayAddMember", far.getid(), null, responseType);
                                pm.makePersistent(tMFAR);
                            }
                        }

                        // TODO: testing restriction HACKER - remove at launch
                        // send alert email
                        String queryMember = "select from " + Member.class.getName() + " where deptId == "
                                + deptId + " && type == 'Hacker' ";
                        List<Member> members = (List<Member>) pm.newQuery(queryMember).execute();

                        //TODO Geocode address to insure easy navigation
                        //TODO johnreilly: add street and town fields to Alert
                        msg.setFrom(
                                new InternetAddress("admin@responderiq05.appspotmail.com", "FirstResponder"));
                        msg.setSubject("Alert!");
                        msg.setText(" Y=" + d.getinboundVRU1() + "&N=" + d.getinboundVRU2() +
                        // "&3=" + d.getinboundVRU3() +  
                                "&A=" + thisAlert.get(0).getalertMsgString());

                        // send message to all dept members who permit tracking (and sending email alerts)
                        for (Member m : members) {
                            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m.getsmsAddress(),
                                    m.getfirstName() + "" + m.getlastName()));
                            log.info("Member: " + m.getsmsAddress() + "|" + m.getlastName());
                        }
                    }
                    // only process for one department - should only be one department
                    break;
                }
            }
        } catch (MessagingException me) {
            log.info("Error: Messaging");
        } catch (IndexOutOfBoundsException mi) {
            log.info("Error: Out of Bounds");
        }

        // Do not send alert notification if email is a Google Confirmation
        //      if (! sender.toString().contains("mail-noreply@google.com")) {
        //        Transport.send(msg);
        //      }

    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } finally {
        pm.close();
    }

}

From source file:com.sonicle.webtop.mail.Service.java

public String getDecodedAddress(Address a) {
    String ret = "";
    try {//ww w  .j ava2 s . co m
        InternetAddress ia = (InternetAddress) a;
        String personal = ia.getPersonal();
        String email = ia.getAddress();
        if (personal == null || personal.equals(email)) {
            ret = email;
        } else {
            ret = personal + " <" + email + ">";
        }
    } catch (RuntimeException exc) {
        ret = a.toString();
    }
    return ret;
}