Example usage for javax.mail.internet MimeMessage getSubject

List of usage examples for javax.mail.internet MimeMessage getSubject

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage getSubject.

Prototype

@Override
public String getSubject() throws MessagingException 

Source Link

Document

Returns the value of the "Subject" header field.

Usage

From source file:mitm.application.djigzo.james.mailets.SMIMEHandlerTest.java

@Test
public void testAddSecurityInfoToSubjectMismatch() throws Exception {
    SMIMEHandler mailet = new SMIMEHandler();

    mailetConfig.setInitParameter("handledProcessor", "handled");

    mailet.init(mailetConfig);/*from   w  w  w  .  j  av a  2  s.c o  m*/

    MockMail mail = new MockMail();

    DjigzoMailAttributesImpl.getInstance(mail).setSecurityInfoTags(
            new SecurityInfoTags("[decrypted]", "[signed]", "[signed by: %s]", "[invalid]"));

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-body-clear-signed.eml"));

    message.setFrom(new InternetAddress("sender@example.com"));

    assertEquals("test simple message", message.getSubject());

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("m.brinkers@pobox.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("test@example.com"));

    mailet.service(mail);

    assertEquals(1, sendMailEventListener.getMails().size());

    Mail newMail = sendMailEventListener.getMails().get(0);

    assertEquals("test simple message [signed by: test@example.com]", newMail.getMessage().getSubject());
}

From source file:edu.stanford.muse.email.EmailFetcherStats.java

/**
 * Key method for importing email: converts a javamail obj. to our own data structure (EmailDocument)
 *//*from  w w  w. j  a v  a2  s.  c o m*/
//public EmailDocument convertToEmailDocument(MimeMessage m, int num, String url) throws MessagingException, IOException
private EmailDocument convertToEmailDocument(MimeMessage m, String id) throws MessagingException, IOException {
    // get the date.
    // prevDate is a hack for the cases where the message is lacking an explicit Date: header. e.g.
    //      From hangal Sun Jun 10 13:46:46 2001
    //      To: ewatkins@stanford.edu
    //      Subject: Re: return value bugs
    // though the date is on the From separator line, the mbox provider fails to parse it and provide it to us.
    // so as a hack, we will assign such messages the same date as the previous one this fetcher has seen! ;-)
    // update: having the exact same date causes the message to be considered a duplicate, so just increment
    // the timestamp it by 1 millisecond!
    // a better fix would be to improve the parsing in the provider

    boolean hackyDate = false;
    Date d = m.getSentDate();
    if (d == null)
        d = m.getReceivedDate();
    if (d == null) {
        if (prevDate != null) {
            long newTime = prevDate.getTime() + 1L; // added +1 so that this email is not considered the same object as the prev. one if they are in the same thread
            d = new Date(newTime);
            dataErrors.add("No date for message id:" + id + ": " + EmailUtils.formatMessageHeader(m)
                    + " assigned approximate date");
        } else {
            d = INVALID_DATE; // wrong, but what can we do... :-(
            dataErrors.add("No date for message id:" + id + ": " + EmailUtils.formatMessageHeader(m)
                    + " assigned deliberately invalid date");
        }
        hackyDate = true;
    } else {
        Calendar c = new GregorianCalendar();
        c.setTime(d);
        int yy = c.get(Calendar.YEAR);
        if (yy < 1960 || yy > 2020) {
            dataErrors.add("Probably bad date: " + Util.formatDate(c) + " message: "
                    + EmailUtils.formatMessageHeader(m));
            hackyDate = true;
        }
    }

    if (hackyDate && prevDate != null) {
        long newTime = prevDate.getTime() + 1L; // added +1 so that this email is not considered the same object as the prev. one if they are in the same thread
        d = new Date(newTime);
        Util.ASSERT(!d.equals(prevDate));
    }

    Calendar c = new GregorianCalendar();
    c.setTime(d != null ? d : new Date());

    prevDate = d;

    Address to[] = null, cc[] = null, bcc[] = null;
    Address[] from = null;
    try {
        //          allrecip = m.getAllRecipients(); // turns out to be too expensive because it looks for newsgroup headers for imap
        // assemble to, cc, bcc into a list and copy it into allrecip
        List<Address> list = new ArrayList<Address>();
        from = m.getFrom();
        to = m.getRecipients(Message.RecipientType.TO);
        if (to != null)
            list.addAll(Arrays.asList(to));
        cc = m.getRecipients(Message.RecipientType.CC);
        if (cc != null)
            list.addAll(Arrays.asList(cc));
        bcc = m.getRecipients(Message.RecipientType.BCC);
        if (bcc != null)
            list.addAll(Arrays.asList(bcc));

        // intern the strings in these addresses to save memory cos they are repeated often in a large archive
        internAddressList(from);
        internAddressList(to);
        internAddressList(cc);
        internAddressList(bcc);
    } catch (AddressException ae) {
        String s = "Bad address in folder " + folder_name() + " message id" + id + " " + ae;
        dataErrors.add(s);
    }

    // take a deep breath. This object is going to live longer than most of us.
    EmailDocument ed = new EmailDocument(id, email_source(), folder_name(), to, cc, bcc, from, m.getSubject(),
            m.getMessageID(), c.getTime());

    String[] headers = m.getHeader("List-Post");
    if (headers != null && headers.length > 0) {
        // trim the headers because they usually look like: "<mailto:prpl-devel@lists.stanford.edu>"
        ed.sentToMailingLists = new String[headers.length];
        int i = 0;
        for (String header : headers) {
            header = header.trim();
            header = header.toLowerCase();

            if (header.startsWith("<") && header.endsWith(">"))
                header = header.substring(1, header.length() - 1);
            if (header.startsWith("mailto:") && !"mailto:".equals(header)) // defensive check in case header == "mailto:"
                header = header.substring(("mailto:").length());
            ed.sentToMailingLists[i++] = header;
        }
    }
    if (hackyDate) {
        String s = "Guessed date " + Util.formatDate(c) + " for message id: " + id + ": " + ed.getHeader();
        dataErrors.add(s);
        ed.hackyDate = true;
    }

    // check if the message has attachments.
    // if it does and we're not downloading attachments, then we mark the ed as such.
    // otherwise we had a problem where a message header (and maybe text) was downloaded but without attachments in one run
    // but in a subsequent run where attachments were needed, we thought the message was already cached and there was no
    // need to recompute it, leaving the attachments field in this ed incorrect.
    List<String> attachmentNames = getAttachmentNames(m, m);
    if (!Util.nullOrEmpty(attachmentNames)) {
        ed.attachmentsYetToBeDownloaded = true; // will set it to false later if attachments really were downloaded (not sure why)
        //         log.info ("added " + attachmentNames.size() + " attachments to message: " + ed);
    }
    return ed;
}

From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

public static String extractInfoMessage(MimeMessage message, Element root, VitamArgument argument,
        ConfigLoader config) {/* w w w  .  j  a  v a  2  s . c  om*/
    File oldDir = argument.currentOutputDir;
    if (argument.currentOutputDir == null) {
        if (config.outputDir != null) {
            argument.currentOutputDir = new File(config.outputDir);
        }
    }
    Element keywords = XmlDom.factory.createElement(EMAIL_FIELDS.keywords.name);
    Element metadata = XmlDom.factory.createElement(EMAIL_FIELDS.metadata.name);
    String skey = "";
    String id = config.addRankId(root);
    Address[] from = null;
    Element sub2 = null;
    try {
        from = message.getFrom();
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("From");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                add.setText(partialResult[0]);
                sub2.add(add);
            }
        } catch (MessagingException e) {
        }
    }
    Address sender = null;
    try {
        sender = message.getSender();
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Sender");
            if (partialResult != null && partialResult.length > 0) {
                if (sub2 == null) {
                    sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                    Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                    add.setText(partialResult[0]);
                    sub2.add(add);
                }
            }
        } catch (MessagingException e) {
        }
    }
    if (from != null && from.length > 0) {
        String value0 = null;
        Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
        if (sender != null) {
            value0 = addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
        }
        for (Address address : from) {
            addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, value0);
        }
        metadata.add(sub);
    } else if (sender != null) {
        Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
        addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
        metadata.add(sub);
    } else {
        if (sub2 != null) {
            metadata.add(sub2);
        }
    }
    Address[] replyTo = null;
    try {
        replyTo = message.getReplyTo();
        if (replyTo != null && replyTo.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
            for (Address address : replyTo) {
                addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("ReplyTo");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
                addAddress(sub2, EMAIL_FIELDS.fromUnit.name, partialResult, null);
                /*Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                add.setText(partialResult[0]);
                sub2.add(add);*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] toRecipients = null;
    try {
        toRecipients = message.getRecipients(Message.RecipientType.TO);
        if (toRecipients != null && toRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
            for (Address address : toRecipients) {
                addAddress(sub, EMAIL_FIELDS.toUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("To");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.toUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.toUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] ccRecipients;
    try {
        ccRecipients = message.getRecipients(Message.RecipientType.CC);
        if (ccRecipients != null && ccRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
            for (Address address : ccRecipients) {
                addAddress(sub, EMAIL_FIELDS.ccUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Cc");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.ccUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.ccUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] bccRecipients;
    try {
        bccRecipients = message.getRecipients(Message.RecipientType.BCC);
        if (bccRecipients != null && bccRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
            for (Address address : bccRecipients) {
                addAddress(sub, EMAIL_FIELDS.bccUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Cc");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.bccUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.bccUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    try {
        String subject = message.getSubject();
        if (subject != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.subject.name);
            sub.setText(StringUtils.unescapeHTML(subject, true, false));
            metadata.add(sub);
        }
        Date sentDate = message.getSentDate();
        if (sentDate != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.sentDate.name);
            sub.setText(sentDate.toString());
            metadata.add(sub);
        }
        Date receivedDate = message.getReceivedDate();
        if (receivedDate != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
            sub.setText(receivedDate.toString());
            metadata.add(sub);
        }
        String[] headers = message.getHeader("Received");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receptionTrace.name);
            MailDateFormat mailDateFormat = null;
            long maxTime = 0;
            if (receivedDate == null) {
                mailDateFormat = new MailDateFormat();
            }
            for (String string : headers) {
                Element sub3 = XmlDom.factory.createElement(EMAIL_FIELDS.trace.name);
                sub3.setText(StringUtils.unescapeHTML(string, true, false));
                sub.add(sub3);
                if (receivedDate == null) {
                    int pos = string.lastIndexOf(';');
                    if (pos > 0) {
                        String recvdate = string.substring(pos + 2).replaceAll("\t\n\r\f", "").trim();
                        try {
                            Date date = mailDateFormat.parse(recvdate);
                            if (date.getTime() > maxTime) {
                                maxTime = date.getTime();
                            }
                        } catch (ParseException e) {
                        }
                    }
                }
            }
            if (receivedDate == null) {
                Element subdate = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
                Date date = new Date(maxTime);
                subdate.setText(date.toString());
                metadata.add(subdate);
            }
            metadata.add(sub);
        }
        int internalSize = message.getSize();
        if (internalSize > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.emailSize.name);
            sub.setText(Integer.toString(internalSize));
            metadata.add(sub);
        }
        String encoding = message.getEncoding();
        if (encoding != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.encoding.name);
            sub.setText(StringUtils.unescapeHTML(encoding, true, false));
            metadata.add(sub);
        }
        String description = message.getDescription();
        if (description != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.description.name);
            sub.setText(StringUtils.unescapeHTML(description, true, false));
            metadata.add(sub);
        }
        String contentType = message.getContentType();
        if (contentType != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentType.name);
            sub.setText(StringUtils.unescapeHTML(contentType, true, false));
            metadata.add(sub);
        }
        headers = message.getHeader("Content-Transfer-Encoding");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentTransferEncoding.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String[] contentLanguage = message.getContentLanguage();
        if (contentLanguage != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentLanguage.name);
            StringBuilder builder = new StringBuilder();
            for (String string : contentLanguage) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String contentId = message.getContentID();
        if (contentId != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentId.name);
            sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(contentId, true, false)));
            metadata.add(sub);
        }
        String disposition = message.getDisposition();
        if (disposition != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.disposition.name);
            sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(disposition, true, false)));
            metadata.add(sub);
        }
        headers = message.getHeader("Keywords");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.msgKeywords.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String messageId = message.getMessageID();
        if (messageId != null) {
            messageId = StringUtils.removeChevron(StringUtils.unescapeHTML(messageId, true, false)).trim();
            if (messageId.length() > 1) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.messageId.name);
                sub.setText(messageId);
                metadata.add(sub);
            }
        }
        headers = message.getHeader("In-Reply-To");
        String inreplyto = null;
        if (headers != null) {
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                builder.append(' ');
            }
            inreplyto = builder.toString().trim();
            if (inreplyto.length() > 0) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.inReplyTo.name);
                sub.setText(inreplyto);
                if (messageId != null && messageId.length() > 1) {
                    String old = filEmls.get(inreplyto);
                    if (old == null) {
                        old = messageId;
                    } else {
                        old += "," + messageId;
                    }
                    filEmls.put(inreplyto, old);
                }
                metadata.add(sub);
            }
        }
        headers = message.getHeader("References");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.references.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                builder.append(' ');
            }
            String[] refs = builder.toString().trim().split(" ");
            for (String string : refs) {
                if (string.length() > 0) {
                    Element ref = XmlDom.factory.createElement(EMAIL_FIELDS.reference.name);
                    ref.setText(string);
                    sub.add(ref);
                }
            }
            metadata.add(sub);
        }
        Element prop = XmlDom.factory.createElement(EMAIL_FIELDS.properties.name);
        headers = message.getHeader("X-Priority");
        if (headers == null) {
            headers = message.getHeader("Priority");
            if (headers != null && headers.length > 0) {
                prop.addAttribute(EMAIL_FIELDS.priority.name, headers[0]);
            }
        } else if (headers != null && headers.length > 0) {
            String imp = headers[0];
            try {
                int Priority = Integer.parseInt(imp);
                switch (Priority) {
                case 5:
                    imp = "LOWEST";
                    break;
                case 4:
                    imp = "LOW";
                    break;
                case 3:
                    imp = "NORMAL";
                    break;
                case 2:
                    imp = "HIGH";
                    break;
                case 1:
                    imp = "HIGHEST";
                    break;
                default:
                    imp = "LEV" + Priority;
                }
            } catch (NumberFormatException e) {
                // ignore since imp will be used as returned
            }
            prop.addAttribute(EMAIL_FIELDS.priority.name, imp);
        }
        headers = message.getHeader("Sensitivity");
        if (headers != null && headers.length > 0) {
            prop.addAttribute(EMAIL_FIELDS.sensitivity.name, headers[0]);
        }
        headers = message.getHeader("X-RDF");
        if (headers != null && headers.length > 0) {
            System.err.println("Found X-RDF");
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(string);
                builder.append("\n");
            }
            try {
                byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(builder.toString());
                String rdf = new String(decoded);
                Document tempDocument = DocumentHelper.parseText(rdf);
                Element xrdf = prop.addElement("x-rdf");
                xrdf.add(tempDocument.getRootElement());
            } catch (Exception e) {
                System.err.println("Cannot decode X-RDF: " + e.getMessage());
            }
        }
        try {
            File old = argument.currentOutputDir;
            if (config.extractFile) {
                File newOutDir = new File(argument.currentOutputDir, id);
                newOutDir.mkdirs();
                argument.currentOutputDir = newOutDir;
            }
            if (argument.extractKeyword) {
                skey = handleMessage(message, metadata, prop, id, argument, config);
                // should have hasAttachment
                if (prop.hasContent()) {
                    metadata.add(prop);
                }
                if (metadata.hasContent()) {
                    root.add(metadata);
                }
                ExtractInfo.exportMetadata(keywords, skey, "", config, null);
                if (keywords.hasContent()) {
                    root.add(keywords);
                }
            } else {
                handleMessage(message, metadata, prop, id, argument, config);
                // should have hasAttachment
                if (prop.hasContent()) {
                    metadata.add(prop);
                }
                if (metadata.hasContent()) {
                    root.add(metadata);
                }
            }
            argument.currentOutputDir = old;
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        }
        try {
            message.getInputStream().close();
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        }
        root.addAttribute(EMAIL_FIELDS.status.name, "ok");
    } catch (MessagingException e) {
        System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        e.printStackTrace();
        String status = "Error during identification";
        root.addAttribute(EMAIL_FIELDS.status.name, status);
    } catch (Exception e) {
        System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        e.printStackTrace();
        String status = "Error during identification";
        root.addAttribute(EMAIL_FIELDS.status.name, status);
    }
    argument.currentOutputDir = oldDir;
    return skey;
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Fetch a message from a folder./* w  w w.  ja  va2 s  .  co  m*/
 * Will put the messages parameters in the sessions environment
 *
 * @param foldername Name of the folder were the message should be fetched from
 * @param msgnum Number of the message to fetch
 * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message
 *             into the current work element of the user and set some additional flags on the message if the user
 *             has enabled this option.
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD
 */
public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException {
    // security reasons:
    // attachments=null;

    try {
        TimeZone tz = TimeZone.getDefault();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
                user.getPreferredLocale());
        df.setTimeZone(tz);
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);

        if (folder == null) {
            throw new NoSuchFolderException("No such folder: " + folderhash);
        }

        if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        } else if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        }

        MimeMessage m = (MimeMessage) folder.getMessage(msgnum);

        String messageid;
        try {
            StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>");
            messageid = tok.nextToken();
        } catch (NullPointerException ex) {
            // For mail servers that don't generate a Message-ID (Outlook et al)
            messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain();
        }

        Element xml_current = model.setCurrentMessage(messageid);
        XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid);

        /* Check whether we already cached this message (not only headers but complete)*/
        boolean cached = xml_message.messageCompletelyCached();
        /* If we cached the message, we don't need to fetch it again */
        if (!cached) {
            //Element xml_header=model.getHeader(xml_message);

            try {
                String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom()));
                String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo()));
                String to = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO)));
                String cc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC)));
                String bcc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC)));
                Date date_orig = m.getSentDate();
                String date = getStringResource("no date");
                if (date_orig != null) {
                    date = df.format(date_orig);
                }
                String subject = "";
                if (m.getSubject() != null) {
                    subject = MimeUtility.decodeText(m.getSubject());
                }
                if (subject == null || subject.equals("")) {
                    subject = getStringResource("no subject");
                }

                try {
                    Flags.Flag[] sf = m.getFlags().getSystemFlags();
                    for (int j = 0; j < sf.length; j++) {
                        if (sf[j] == Flags.Flag.RECENT)
                            xml_message.setAttribute("recent", "true");
                        if (sf[j] == Flags.Flag.SEEN)
                            xml_message.setAttribute("seen", "true");
                        if (sf[j] == Flags.Flag.DELETED)
                            xml_message.setAttribute("deleted", "true");
                        if (sf[j] == Flags.Flag.ANSWERED)
                            xml_message.setAttribute("answered", "true");
                        if (sf[j] == Flags.Flag.DRAFT)
                            xml_message.setAttribute("draft", "true");
                        if (sf[j] == Flags.Flag.FLAGGED)
                            xml_message.setAttribute("flagged", "true");
                        if (sf[j] == Flags.Flag.USER)
                            xml_message.setAttribute("user", "true");
                    }
                } catch (NullPointerException ex) {
                }
                if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                    xml_message.setAttribute("attachment", "true");
                }

                int size = m.getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");

                /* Set all of what we found into the DOM */
                xml_message.setHeader("FROM", from);
                xml_message.setHeader("SUBJECT", Fancyfier.apply(subject));
                xml_message.setHeader("TO", to);
                xml_message.setHeader("CC", cc);
                xml_message.setHeader("BCC", bcc);
                xml_message.setHeader("REPLY-TO", replyto);
                xml_message.setHeader("DATE", date);

                /* Decode MIME contents recursively */
                xml_message.removeAllParts();
                parseMIMEContent(m, xml_message, messageid);

            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage());
            }
        }
        /* Set seen flag (Maybe make that threaded to improve performance) */
        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true);
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false);
            if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true);
            }
        }
        folder.close(false);

        /* In this part we determine whether the message was requested so that it may be used for
           further editing (replying or forwarding). In this case we set the current "work" message to the
           message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */
        XMLMessage work = null;
        if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY
                || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
            log.debug("Setting work message!");
            work = model.setWorkMessage(xml_message);

            String newmsgid = WebMailServer.generateMessageID(user.getUserName());

            if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", from);
                work.prepareReply(getStringResource("reply subject prefix"),
                        getStringResource("reply subject postfix"), getStringResource("reply message prefix"),
                        getStringResource("reply message postfix"));

            } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", "");
                work.setHeader("CC", "");
                work.prepareForward(getStringResource("forward subject prefix"),
                        getStringResource("forward subject postfix"),
                        getStringResource("forward message prefix"),
                        getStringResource("forward message postfix"));

                /* Copy all references to MIME parts to the new message id */
                for (String key : getMimeParts(work.getAttribute("msgid"))) {
                    StringTokenizer tok2 = new StringTokenizer(key, "/");
                    tok2.nextToken();
                    String newkey = tok2.nextToken();
                    mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key));
                }
            }

            /* Clear the msgnr and msgid fields at last */
            work.setAttribute("msgnr", "0");
            work.setAttribute("msgid", newmsgid);
            prepareCompose();
        }
    } catch (MessagingException ex) {
        log.error("Failed to get message.  Doing nothing instead.", ex);
    }
}

From source file:org.alfresco.email.server.impl.subetha.SubethaEmailMessage.java

private void processMimeMessage(MimeMessage mimeMessage) {
    if (from == null) {
        Address[] addresses = null;//from   www.  jav  a2  s .  c o m
        try {
            addresses = mimeMessage.getFrom();
        } catch (MessagingException e) {
            throw new EmailMessageException(ERR_EXTRACTING_FROM_ADDRESS, e.getMessage());
        }
        if (addresses == null || addresses.length == 0) {
            //throw new EmailMessageException(ERR_NO_FROM_ADDRESS);
        } else {
            if (addresses[0] instanceof InternetAddress) {
                from = ((InternetAddress) addresses[0]).getAddress();
            } else {
                from = addresses[0].toString();
            }
        }
    }

    if (to == null) {
        Address[] addresses = null;
        try {
            addresses = mimeMessage.getAllRecipients();
        } catch (MessagingException e) {
            throw new EmailMessageException(ERR_EXTRACTING_TO_ADDRESS, e.getMessage());
        }
        if (addresses == null || addresses.length == 0) {
            //throw new EmailMessageException(ERR_NO_TO_ADDRESS);
        } else {
            if (addresses[0] instanceof InternetAddress) {
                to = ((InternetAddress) addresses[0]).getAddress();
            } else {
                to = addresses[0].toString();
            }
        }
    }

    if (cc == null) {
        try {
            ArrayList<String> list = new ArrayList<String>();

            Address[] cca = mimeMessage.getRecipients(RecipientType.CC);

            if (cca != null) {
                for (Address a : cca) {
                    list.add(a.toString());
                }
            }
            cc = list;
        } catch (MessagingException e) {
            // Do nothing - this is not a show-stopper.
            cc = null;
        }
    }

    try {
        subject = mimeMessage.getSubject();
        //subject = encodeSubject(mimeMessage.getSubject());
    } catch (MessagingException e) {
        throw new EmailMessageException(ERR_EXTRACTING_SUBJECT, e.getMessage());
    }
    //if (subject == null)
    //{
    //    subject = ""; // Just anti-null stub :)
    //}

    try {
        sentDate = mimeMessage.getSentDate();
    } catch (MessagingException e) {
        throw new EmailMessageException(ERR_EXTRACTING_SENT_DATE, e.getMessage());
    }
    if (sentDate == null) {
        sentDate = new Date(); // Just anti-null stub :)
    }

    parseMessagePart(mimeMessage);
    attachments = new EmailMessagePart[attachmentList.size()];
    attachmentList.toArray(attachments);
    attachmentList = null;
}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Extracts properties and text from an EML Document input stream.
 *
 * @param stream//from  ww  w  .  jav  a 2s  . c om
 *            the stream
 * @param handler
 *            the handler
 * @param metadata
 *            the metadata
 * @param context
 *            the context
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 */
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();

    Properties props = System.getProperties();
    Session mailSession = Session.getDefaultInstance(props, null);

    try {
        MimeMessage message = new MimeMessage(mailSession, stream);

        String subject = message.getSubject();
        String from = this.convertAddressesToString(message.getFrom());
        // Recipients :
        String messageException = "";
        String to = "";
        String cc = "";
        String bcc = "";
        try {
            // QVIDMS-2004 Added because of bug in Mail Api
            to = this.convertAddressesToString(message.getRecipients(Message.RecipientType.TO));
            cc = this.convertAddressesToString(message.getRecipients(Message.RecipientType.CC));
            bcc = this.convertAddressesToString(message.getRecipients(Message.RecipientType.BCC));
        } catch (AddressException e) {
            e.printStackTrace();
            messageException = e.getRef();
            if (messageException.indexOf("recipients:") != -1) {
                to = messageException.substring(0, messageException.indexOf(":"));
            }
        }
        metadata.set(Office.AUTHOR, from);
        metadata.set(DublinCore.TITLE, subject);
        metadata.set(DublinCore.SUBJECT, subject);

        xhtml.element("h1", subject);

        xhtml.startElement("dl");
        header(xhtml, "From", MimeUtility.decodeText(from));
        header(xhtml, "To", MimeUtility.decodeText(to.toString()));
        header(xhtml, "Cc", MimeUtility.decodeText(cc.toString()));
        header(xhtml, "Bcc", MimeUtility.decodeText(bcc.toString()));

        // // Parse message
        // if (message.getContent() instanceof MimeMultipart) {
        // // Multipart message, call matching method
        // MimeMultipart multipart = (MimeMultipart) message.getContent();
        // this.extractMultipart(xhtml, multipart, context);

        List<String> attachmentList = new ArrayList<String>();
        // prepare attachments
        prepareExtractMultipart(xhtml, message, null, context, attachmentList);
        if (attachmentList.size() > 0) {
            // TODO internationalization
            header(xhtml, "Attachments", attachmentList.toString());
        }
        xhtml.endElement("dl");

        // a supprimer si pb et a remplacer par ce qui est commenT
        adaptedExtractMultipart(xhtml, message, null, context);

        xhtml.endDocument();
    } catch (Exception e) {
        throw new TikaException("Error while processing message", e);
    }
}

From source file:org.alfresco.repo.invitation.AbstractInvitationServiceImplTest.java

/**
 * Test nominated user - new user//from ww  w  .ja  v  a 2  s.  c  o  m
 * 
 * @throws Exception
 */
public void testNominatedInvitationNewUser() throws Exception {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.SECOND, -1);
    Date startDate = calendar.getTime();

    String inviteeFirstName = PERSON_FIRSTNAME;
    String inviteeLastName = PERSON_LASTNAME;
    String inviteeEmail = "123@alfrescotesting.com";
    String inviteeUserName = null;
    Invitation.ResourceType resourceType = Invitation.ResourceType.WEB_SITE;
    String resourceName = SITE_SHORT_NAME_INVITE;
    String inviteeRole = SiteModel.SITE_COLLABORATOR;
    String serverPath = "wibble";
    String acceptUrl = "froob";
    String rejectUrl = "marshmallow";

    this.authenticationComponent.setCurrentUser(USER_MANAGER);

    NominatedInvitation nominatedInvitation = invitationService.inviteNominated(inviteeFirstName,
            inviteeLastName, inviteeEmail, resourceType, resourceName, inviteeRole, serverPath, acceptUrl,
            rejectUrl);

    assertNotNull("nominated invitation is null", nominatedInvitation);
    String inviteId = nominatedInvitation.getInviteId();
    assertEquals("first name wrong", inviteeFirstName, nominatedInvitation.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, nominatedInvitation.getInviteeLastName());
    assertEquals("email name wrong", inviteeEmail, nominatedInvitation.getInviteeEmail());

    // Generated User Name should be returned
    inviteeUserName = nominatedInvitation.getInviteeUserName();
    assertNotNull("generated user name is null", inviteeUserName);
    // sentInviteDate should be set to today
    {
        Date sentDate = nominatedInvitation.getSentInviteDate();
        assertTrue("sentDate wrong - too early. Start Date: " + startDate + "\nSent Date: " + sentDate,
                sentDate.after(startDate));
        assertTrue("sentDate wrong - too lateStart Date: " + startDate + "\nSent Date: " + sentDate,
                sentDate.before(new Date(new Date().getTime() + 1)));
    }

    assertEquals("resource type name wrong", resourceType, nominatedInvitation.getResourceType());
    assertEquals("resource name wrong", resourceName, nominatedInvitation.getResourceName());
    assertEquals("role  name wrong", inviteeRole, nominatedInvitation.getRoleName());
    assertEquals("server path wrong", serverPath, nominatedInvitation.getServerPath());
    assertEquals("accept URL wrong", acceptUrl, nominatedInvitation.getAcceptUrl());
    assertEquals("reject URL wrong", rejectUrl, nominatedInvitation.getRejectUrl());

    /**
     * Now we have an invitation get it and check the details have been
     * returned correctly.
     */
    {
        NominatedInvitation invitation = (NominatedInvitation) invitationService.getInvitation(inviteId);

        assertNotNull("invitation is null", invitation);
        assertEquals("invite id wrong", inviteId, invitation.getInviteId());
        assertEquals("first name wrong", inviteeFirstName, invitation.getInviteeFirstName());
        assertEquals("last name wrong", inviteeLastName, invitation.getInviteeLastName());
        assertEquals("user name wrong", inviteeUserName, invitation.getInviteeUserName());
        assertEquals("resource type name wrong", resourceType, invitation.getResourceType());
        assertEquals("resource name wrong", resourceName, invitation.getResourceName());
        assertEquals("role  name wrong", inviteeRole, invitation.getRoleName());
        assertEquals("server path wrong", serverPath, invitation.getServerPath());
        assertEquals("accept URL wrong", acceptUrl, invitation.getAcceptUrl());
        assertEquals("reject URL wrong", rejectUrl, invitation.getRejectUrl());

        Date sentDate = invitation.getSentInviteDate();
        // sentInviteDate should be set to today
        assertTrue("sentDate wrong too early", sentDate.after(startDate));
        assertTrue("sentDate wrong - too late", sentDate.before(new Date(new Date().getTime() + 1)));
    }

    /**
     * Check the email itself, and check it
     *  is as we would expect it to be
     */
    {
        MimeMessage msg = mailService.retrieveLastTestMessage();

        assertEquals(1, msg.getAllRecipients().length);
        assertEquals(inviteeEmail, msg.getAllRecipients()[0].toString());

        assertEquals(1, msg.getFrom().length);
        assertEquals(USER_MANAGER + "@alfrescotesting.com", msg.getFrom()[0].toString());

        // Hasn't been sent, so no sent or received date
        assertNull("Not been sent yet", msg.getSentDate());
        assertNull("Not been sent yet", msg.getReceivedDate());

        // TODO - check some more details of the email
        assertTrue((msg.getSubject().indexOf("You have been invited to join the") != -1));
    }

    /**
     * Search for the new invitation
     */
    List<Invitation> invitations = invitationService.listPendingInvitationsForResource(resourceType,
            resourceName);
    assertTrue("invitations is empty", !invitations.isEmpty());

    NominatedInvitation firstInvite = (NominatedInvitation) invitations.get(0);
    assertEquals("invite id wrong", inviteId, firstInvite.getInviteId());
    assertEquals("first name wrong", inviteeFirstName, firstInvite.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, firstInvite.getInviteeLastName());
    assertEquals("user name wrong", inviteeUserName, firstInvite.getInviteeUserName());

    /**
     * Now accept the invitation
     */
    NominatedInvitation acceptedInvitation = (NominatedInvitation) invitationService
            .accept(firstInvite.getInviteId(), firstInvite.getTicket());
    assertEquals("invite id wrong", firstInvite.getInviteId(), acceptedInvitation.getInviteId());
    assertEquals("first name wrong", inviteeFirstName, acceptedInvitation.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, acceptedInvitation.getInviteeLastName());
    assertEquals("user name wrong", inviteeUserName, acceptedInvitation.getInviteeUserName());

    List<Invitation> it4 = invitationService.listPendingInvitationsForResource(resourceType, resourceName);
    assertTrue("invitations is not empty", it4.isEmpty());

    /**
     * Now get the invitation that we accepted
     */
    NominatedInvitation acceptedInvitation2 = (NominatedInvitation) invitationService
            .getInvitation(firstInvite.getInviteId());
    assertNotNull("get after accept does not return", acceptedInvitation2);

    /**
     * Now verify access control list
     */
    String roleName = siteService.getMembersRole(resourceName, inviteeUserName);
    assertEquals("role name wrong", roleName, inviteeRole);
    siteService.removeMembership(resourceName, inviteeUserName);

    /**
     * Check that system generated invitations can work as well
     */
    {
        Field faf = mailService.getClass().getDeclaredField("fromAddress");
        faf.setAccessible(true);
        String defaultFromAddress = (String) ReflectionUtils.getField(faf, mailService);

        AuthenticationUtil.setFullyAuthenticatedUser(USER_NOEMAIL);

        // Check invitiation
        NominatedInvitation nominatedInvitation2 = invitationService.inviteNominated(inviteeFirstName,
                inviteeLastName, USER_TWO_EMAIL, resourceType, resourceName, inviteeRole, serverPath, acceptUrl,
                rejectUrl);

        assertNotNull("nominated invitation is null", nominatedInvitation2);
        inviteId = nominatedInvitation.getInviteId();
        assertEquals("first name wrong", inviteeFirstName, nominatedInvitation2.getInviteeFirstName());
        assertEquals("last name wrong", inviteeLastName, nominatedInvitation2.getInviteeLastName());
        assertEquals("email name wrong", USER_TWO_EMAIL, nominatedInvitation2.getInviteeEmail());

        // Check the email
        MimeMessage msg = mailService.retrieveLastTestMessage();

        assertEquals(1, msg.getAllRecipients().length);
        assertEquals(USER_TWO_EMAIL, msg.getAllRecipients()[0].toString());

        assertEquals(1, msg.getFrom().length);
        assertEquals(defaultFromAddress, msg.getFrom()[0].toString());
    }
}

From source file:org.alfresco.repo.security.authentication.ResetPasswordServiceImplTest.java

@Test
public void testResetPassword() throws Exception {
    // Try the credential before change of password
    authenticateUser(testPerson.userName, testPerson.password);

    // Make sure to run as system
    AuthenticationUtil.clearCurrentSecurityContext();
    AuthenticationUtil.setRunAsUserSystem();

    // Request password reset
    resetPasswordService.requestReset(testPerson.userName, "share");
    assertEquals("A reset password email should have been sent.", 1, emailUtil.getSentCount());
    // Check the email
    MimeMessage msg = emailUtil.getLastEmail();
    assertNotNull("There should be an email.", msg);
    assertEquals("Should've been only one email recipient.", 1, msg.getAllRecipients().length);
    // Check the recipient is the person who requested the reset password
    assertEquals(testPerson.email, msg.getAllRecipients()[0].toString());
    //Check the sender is what we set as default
    assertEquals(DEFAULT_SENDER, msg.getFrom()[0].toString());
    // There should be a subject
    assertNotNull("There should be a subject.", msg.getSubject());
    // Check the default email subject - (check that we are sending the right email)
    String emailSubjectKey = getDeclaredField(SendResetPasswordEmailDelegate.class, "EMAIL_SUBJECT_KEY");
    assertNotNull(emailSubjectKey);/*ww w  .j  a  v a  2 s  .c  o  m*/
    assertEquals(msg.getSubject(), I18NUtil.getMessage(emailSubjectKey));

    // Check the reset password url.
    String resetPasswordUrl = (String) emailUtil.getLastEmailTemplateModelValue("reset_password_url");
    assertNotNull("Wrong email is sent.", resetPasswordUrl);
    // Get the workflow id and key
    Pair<String, String> pair = getWorkflowIdAndKeyFromUrl(resetPasswordUrl);
    assertNotNull("Workflow Id can't be null.", pair.getFirst());
    assertNotNull("Workflow Key can't be null.", pair.getSecond());

    emailUtil.reset();
    // Now that we have got the email, try to reset the password
    ResetPasswordDetails passwordDetails = new ResetPasswordDetails().setUserId(testPerson.userName)
            .setPassword("newPassword").setWorkflowId(pair.getFirst()).setWorkflowKey(pair.getSecond());

    resetPasswordService.initiateResetPassword(passwordDetails);
    assertEquals("A reset password confirmation email should have been sent.", 1, emailUtil.getSentCount());
    // Check the email
    msg = emailUtil.getLastEmail();
    assertNotNull("There should be an email.", msg);
    assertEquals("Should've been only one email recipient.", 1, msg.getAllRecipients().length);
    // Check the recipient is the person who requested the reset password
    assertEquals(testPerson.email, msg.getAllRecipients()[0].toString());
    // Check the sender is what we set as default
    assertEquals(DEFAULT_SENDER, msg.getFrom()[0].toString());
    // There should be a subject
    assertNotNull("There should be a subject.", msg.getSubject());
    // Check the default email subject - (check that we are sending the right email)
    emailSubjectKey = getDeclaredField(SendResetPasswordConfirmationEmailDelegate.class, "EMAIL_SUBJECT_KEY");
    assertNotNull(emailSubjectKey);
    assertEquals(msg.getSubject(), I18NUtil.getMessage(emailSubjectKey));

    // Try the old credential
    TestHelper.assertThrows(() -> authenticateUser(testPerson.userName, testPerson.password),
            AuthenticationException.class,
            "As the user changed her password, the authentication should have failed.");

    // Try the new credential
    authenticateUser(testPerson.userName, "newPassword");

    // Make sure to run as system
    AuthenticationUtil.clearCurrentSecurityContext();
    AuthenticationUtil.setRunAsUserSystem();
    emailUtil.reset();
    // Try reset again with the used workflow
    TestHelper.assertThrows(() -> resetPasswordService.initiateResetPassword(passwordDetails),
            InvalidResetPasswordWorkflowException.class,
            "The workflow instance is not active (it has already been used).");
    assertEquals("No email should have been sent.", 0, emailUtil.getSentCount());
}

From source file:org.apache.axis2.transport.mail.MailClient.java

public int checkInbox(int mode) throws MessagingException, IOException {
    int numMessages = 0;

    if (mode == 0) {
        return 0;
    }//from www  . j a v a2s.c o  m

    boolean show = (mode & SHOW_MESSAGES) > 0;
    boolean clear = (mode & CLEAR_MESSAGES) > 0;
    String action = (show ? "Show" : "") + ((show && clear) ? " and " : "") + (clear ? "Clear" : "");

    log.info(action + " INBOX for " + from);

    Store store = session.getStore();

    store.connect();

    Folder root = store.getDefaultFolder();
    Folder inbox = root.getFolder("inbox");

    inbox.open(Folder.READ_WRITE);

    Message[] msgs = inbox.getMessages();

    numMessages = msgs.length;

    if ((msgs.length == 0) && show) {
        log.info("No messages in inbox");
    }

    for (int i = 0; i < msgs.length; i++) {
        MimeMessage msg = (MimeMessage) msgs[i];

        if (show) {
            log.info("    From: " + msg.getFrom()[0]);
            log.info(" Subject: " + msg.getSubject());
            log.info(" Content: " + msg.getContent());
        }

        if (clear) {
            msg.setFlag(Flags.Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();

    return numMessages;
}

From source file:org.apache.axis2.transport.mail.server.MailSorter.java

public void processMail(ConfigurationContext confContext, MimeMessage mimeMessage) {
    // create an Axis server
    AxisEngine engine = new AxisEngine(confContext);
    MessageContext msgContext = null;

    // create and initialize a message context
    try {// ww w.  jav a  2  s. c  om
        msgContext = confContext.createMessageContext();
        msgContext.setTransportIn(
                confContext.getAxisConfiguration().getTransportIn(org.apache.axis2.Constants.TRANSPORT_MAIL));
        msgContext.setTransportOut(
                confContext.getAxisConfiguration().getTransportOut(org.apache.axis2.Constants.TRANSPORT_MAIL));

        msgContext.setServerSide(true);
        msgContext.setProperty(Constants.CONTENT_TYPE, mimeMessage.getContentType());
        msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING,
                mimeMessage.getEncoding());
        String soapAction = getMailHeader(Constants.HEADER_SOAP_ACTION, mimeMessage);
        if (soapAction == null) {
            soapAction = mimeMessage.getSubject();
        }

        msgContext.setSoapAction(soapAction);
        msgContext.setIncomingTransportName(org.apache.axis2.Constants.TRANSPORT_MAIL);

        String serviceURL = mimeMessage.getSubject();

        if (serviceURL == null) {
            serviceURL = "";
        }

        String replyTo = ((InternetAddress) mimeMessage.getReplyTo()[0]).getAddress();

        if (replyTo != null) {
            msgContext.setReplyTo(new EndpointReference(replyTo));
        }

        String recepainets = ((InternetAddress) mimeMessage.getAllRecipients()[0]).getAddress();

        if (recepainets != null) {
            msgContext.setTo(new EndpointReference(recepainets + "/" + serviceURL));
        }

        // add the SOAPEnvelope
        String message = mimeMessage.getContent().toString();

        log.info("message[" + message + "]");

        ByteArrayInputStream bais = new ByteArrayInputStream(message.getBytes());
        String soapNamespaceURI = "";

        if (mimeMessage.getContentType().indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
            soapNamespaceURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
        } else if (mimeMessage.getContentType().indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) {
            soapNamespaceURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
        }

        StAXBuilder builder = BuilderUtil.getSOAPBuilder(bais, soapNamespaceURI);

        SOAPEnvelope envelope = (SOAPEnvelope) builder.getDocumentElement();

        msgContext.setEnvelope(envelope);

        AxisEngine.receive(msgContext);
    } catch (Exception e) {
        try {
            if (msgContext != null) {
                MessageContext faultContext = MessageContextBuilder.createFaultMessageContext(msgContext, e);

                engine.sendFault(faultContext);
            }
        } catch (Exception e1) {
            log.error(e.getMessage(), e);
        }
    }
}