Example usage for javax.mail.internet MimeMessage getRecipients

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

Introduction

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

Prototype

@Override
public Address[] getRecipients(Message.RecipientType type) throws MessagingException 

Source Link

Document

Returns the recepients specified by the type.

Usage

From source file:fi.foyt.fni.test.ui.base.gamelibrary.GameLibraryProposeGameTestsBase.java

@Test
@SqlSets("basic-users")
public void testPropose() throws Exception {
    if ("chrome".equals(getBrowser())) {
        // FIXME: File uploading fails with bad gateway on Sauce Labs when using Chrome.
        return;//from  ww  w. j a v a  2  s  .c o  m
    }

    loginInternal("user@foyt.fi", "pass");
    navigate("/gamelibrary/proposegame/");

    File testPng = getTestPng();
    File testPdf = getTestPdf();

    waitAndSendKeys(".gamelibrary-propose-game-form-name", "My awesome game");
    waitAndSendKeys(".gamelibrary-propose-game-form-description", "This game is just pretty awesome");
    waitAndSendKeys(".gamelibrary-propose-game-form-authors-share", "5");

    waitAndSendKeys(".gamelibrary-propose-game-form-section-image input[name='file']",
            testPng.getAbsolutePath());
    waitForSelectorPresent(".gamelibrary-propose-game-form-section-image .upload-field-file-name");
    assertSelectorCount(".gamelibrary-propose-game-form-section-image .upload-field-file-name", 1);
    assertSelectorText(".gamelibrary-propose-game-form-section-image .upload-field-file-name",
            testPng.getName(), true, true);

    waitAndSendKeys(".gamelibrary-propose-game-form-section-downloadable input[name='file']",
            testPdf.getAbsolutePath());
    waitForSelectorPresent(".gamelibrary-propose-game-form-section-downloadable .upload-field-file-name");
    assertSelectorCount(".gamelibrary-propose-game-form-section-downloadable .upload-field-file-name", 1);
    assertSelectorText(".gamelibrary-propose-game-form-section-downloadable .upload-field-file-name",
            testPdf.getName(), true, true);

    waitAndSendKeys(".gamelibrary-propose-game-form-section-printable input[name='file']",
            testPdf.getAbsolutePath());
    waitForSelectorPresent(".gamelibrary-propose-game-form-section-printable .upload-field-file-name");
    assertSelectorCount(".gamelibrary-propose-game-form-section-printable .upload-field-file-name", 1);
    assertSelectorText(".gamelibrary-propose-game-form-section-printable .upload-field-file-name",
            testPdf.getName(), true, true);

    waitAndClick(".gamelibrary-propose-game-send");

    MimeMessage[] messages = getGreenMail().getReceivedMessages();
    assertEquals(2, messages.length);

    List<String> recipientAddressses = new ArrayList<>();

    for (MimeMessage message : messages) {
        assertEquals("New Publication into the Game Library", message.getSubject());
        assertTrue(StringUtils.contains((String) message.getContent(),
                "Test User (user@foyt.fi) has proposed that My awesome game"));
        Address[] recipients = message.getRecipients(RecipientType.TO);

        for (Address recipient : recipients) {
            String address = ((InternetAddress) recipient).getAddress();
            if (!recipientAddressses.contains(address)) {
                recipientAddressses.add(address);
            }
        }

    }

    assertEquals(Arrays.asList("librarian@foyt.fi", "admin@foyt.fi"), recipientAddressses);

    waitForSelectorVisible(".gamelibrary-publication h3 a");

    assertSelectorText(".gamelibrary-publication h3 a", "My awesome game", true, true);
    assertSelectorText(".gamelibrary-publication .gamelibrary-publication-description",
            "This game is just pretty awesome", true, true);

    executeSql(
            "update PublicationFile set contentType = 'DELETE' where id in (select printableFile_id from BookPublication where id in (select id from Publication where creator_id = ?) union select downloadableFile_id from BookPublication where id in (select id from Publication where creator_id = ?))",
            2, 2);
    executeSql("update Publication set defaultImage_id = null where creator_id = ?", 2);
    executeSql(
            "Update BookPublication set printableFile_id = null, downloadableFile_id = null where id in (select id from Publication where creator_id = ?)",
            2);
    executeSql(
            "delete from PublicationImage where publication_id in (select id from Publication where creator_id = ?)",
            2);
    executeSql("delete from PublicationFile where contentType = 'DELETE'");
    executeSql("delete from BookPublication where id in (select id from Publication where creator_id = ?)", 2);
    executeSql("delete from Publication where creator_id = ?", 2);
}

From source file:com.zimbra.cs.mime.Mime.java

/**
 * Remove all email addresses in rcpts from To/Cc/Bcc headers of a
 * MimeMessage./*from   w  w  w  .j a  v a  2s  . c  o m*/
 * @param mm
 * @param rcpts
 * @throws MessagingException
 */
public static void removeRecipients(MimeMessage mm, String[] rcpts) throws MessagingException {
    for (RecipientType rcptType : sRcptTypes) {
        Address[] addrs = mm.getRecipients(rcptType);
        if (addrs == null)
            continue;
        ArrayList<InternetAddress> list = new ArrayList<InternetAddress>(addrs.length);
        for (int j = 0; j < addrs.length; j++) {
            InternetAddress inetAddr = (InternetAddress) addrs[j];
            String addr = inetAddr.getAddress();
            boolean match = false;
            for (int k = 0; k < rcpts.length; k++)
                if (addr.equalsIgnoreCase(rcpts[k]))
                    match = true;
            if (!match)
                list.add(inetAddr);
        }
        if (list.size() < addrs.length) {
            InternetAddress[] newRcpts = new InternetAddress[list.size()];
            list.toArray(newRcpts);
            mm.setRecipients(rcptType, newRcpts);
        }
    }
}

From source file:at.gv.egovernment.moa.id.configuration.helper.MailHelper.java

private static void sendMail(ConfigurationProvider config, String subject, String recipient, String content)
        throws ConfigurationException {
    try {//from www  . ja  v a  2s. co  m
        log.debug("Sending mail.");
        MiscUtil.assertNotNull(subject, "subject");
        MiscUtil.assertNotNull(recipient, "recipient");
        MiscUtil.assertNotNull(content, "content");

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", config.getSMTPMailHost());
        log.trace("Mail host: " + config.getSMTPMailHost());
        if (config.getSMTPMailPort() != null) {
            log.trace("Mail port: " + config.getSMTPMailPort());
            props.setProperty("mail.port", config.getSMTPMailPort());
        }
        if (config.getSMTPMailUsername() != null) {
            log.trace("Mail user: " + config.getSMTPMailUsername());
            props.setProperty("mail.user", config.getSMTPMailUsername());
        }
        if (config.getSMTPMailPassword() != null) {
            log.trace("Mail password: " + config.getSMTPMailPassword());
            props.setProperty("mail.password", config.getSMTPMailPassword());
        }

        Session mailSession = Session.getDefaultInstance(props, null);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject);
        log.trace("Mail from: " + config.getMailFromName() + "/" + config.getMailFromAddress());
        message.setFrom(new InternetAddress(config.getMailFromAddress(), config.getMailFromName()));
        log.trace("Recipient: " + recipient);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

        log.trace("Creating multipart content of mail.");
        MimeMultipart multipart = new MimeMultipart("related");

        log.trace("Adding first part (html)");
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=ISO-8859-15");
        multipart.addBodyPart(messageBodyPart);

        //         log.trace("Adding mail images");
        //         messageBodyPart = new MimeBodyPart();
        //         for (Image image : images) {
        //            messageBodyPart.setDataHandler(new DataHandler(image));
        //            messageBodyPart.setHeader("Content-ID", "<" + image.getContentId() + ">");
        //            multipart.addBodyPart(messageBodyPart);
        //         }

        message.setContent(multipart);
        transport.connect();
        log.trace("Sending mail message.");
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        log.trace("Successfully sent.");
        transport.close();

    } catch (MessagingException e) {
        throw new ConfigurationException(e);

    } catch (UnsupportedEncodingException e) {
        throw new ConfigurationException(e);

    }
}

From source file:com.basicservice.service.MailService.java

public void sendEmail(String from, String to, String subject, String messageHtml) throws Exception {
    try {/*from   www . j  av a 2  s . c  o  m*/
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", 587);
        props.put("mail.smtp.auth", "true");
        Authenticator auth = new SMTPAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        // mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        Multipart multipart = new MimeMultipart("alternative");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(new String(messageHtml.getBytes("UTF8"), "ISO-8859-1"), "text/html");
        multipart.addBodyPart(htmlPart);

        message.setContent(multipart);
        message.setFrom(new InternetAddress(from));
        message.setSubject(subject, "UTF-8");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        transport.connect();
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        transport.close();
    } catch (Exception e) {
        LOG.debug("Exception while sending email: ", e);
        throw e;
    }
}

From source file:com.gcrm.util.mail.MailService.java

public void sendHtmlMail(String from, String[] to, String subject, String text, String[] fileNames,
        File[] files) throws Exception {
    List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName());
    EmailSetting emailSetting = null;//ww  w .  j  a va 2  s. c  o m
    if (emailSettings != null && emailSettings.size() > 0) {
        emailSetting = emailSettings.get(0);
    } else {
        return;
    }
    if (from == null) {
        from = emailSetting.getFrom_address();
    }
    Session mailSession = createSmtpSession(emailSetting);

    if (mailSession != null) {
        Transport transport = mailSession.getTransport();
        MimeMessage msg = new MimeMessage(mailSession);
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text, true);
        if (fileNames != null && files != null) {
            String fileName = null;
            File file = null;
            for (int i = 0; i < fileNames.length; i++) {
                fileName = fileNames[i];
                file = files[i];
                if (fileName != null && file != null) {
                    helper.addAttachment(fileName, file);
                }
            }
        }
        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
    }

}

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);//  w w w  .  j av  a  2s . c o  m
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

    // add the Multipart to the message
    message.setContent(mp);

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

From source file:mitm.common.pdf.MessagePDFBuilder.java

public void buildPDF(MimeMessage message, String replyURL, OutputStream pdfStream)
        throws DocumentException, MessagingException, IOException {
    Document document = createDocument();

    PdfWriter pdfWriter = createPdfWriter(document, pdfStream);

    document.open();/*from ww w.j  ava  2  s .  c  o  m*/

    String[] froms = null;

    try {
        froms = EmailAddressUtils.addressesToStrings(message.getFrom(), true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("From address is not a valid email address.");
    }

    if (froms != null) {
        for (String from : froms) {
            document.addAuthor(from);
        }
    }

    String subject = null;

    try {
        subject = message.getSubject();
    } catch (MessagingException e) {
        logger.error("Error getting subject.", e);
    }

    if (subject != null) {
        document.addSubject(subject);
        document.addTitle(subject);
    }

    String[] tos = null;

    try {
        tos = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.TO),
                true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("To is not a valid email address.");
    }

    String[] ccs = null;

    try {
        ccs = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.CC),
                true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("CC is not a valid email address.");
    }

    Date sentDate = null;

    try {
        sentDate = message.getSentDate();
    } catch (MessagingException e) {
        logger.error("Error getting sent date.", e);
    }

    Collection<Part> attachments = new LinkedList<Part>();

    String body = BodyPartUtils.getPlainBodyAndAttachments(message, attachments);

    attachments = preprocessAttachments(attachments);

    if (body == null) {
        body = MISSING_BODY;
    }

    /*
     * PDF does not have tab support so we convert tabs to spaces
     */
    body = StringReplaceUtils.replaceTabsWithSpaces(body, tabWidth);

    PdfPTable headerTable = new PdfPTable(2);

    headerTable.setHorizontalAlignment(Element.ALIGN_LEFT);
    headerTable.setWidthPercentage(100);
    headerTable.setWidths(new int[] { 1, 6 });
    headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

    Font headerFont = createHeaderFont();

    FontSelector headerFontSelector = createHeaderFontSelector();

    PdfPCell cell = new PdfPCell(new Paragraph("From:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);

    String decodedFroms = StringUtils.defaultString(StringUtils.join(froms, ", "));

    headerTable.addCell(headerFontSelector.process(decodedFroms));

    cell = new PdfPCell(new Paragraph("To:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(tos, ", "))));

    cell = new PdfPCell(new Paragraph("CC:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(ccs, ", "))));

    cell = new PdfPCell(new Paragraph("Subject:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(subject)));

    cell = new PdfPCell(new Paragraph("Date:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(ObjectUtils.toString(sentDate));

    cell = new PdfPCell(new Paragraph("Attachments:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable
            .addCell(headerFontSelector.process(StringUtils.defaultString(getAttachmentHeader(attachments))));

    document.add(headerTable);

    if (replyURL != null) {
        addReplyLink(document, replyURL);
    }

    /*
     * Body table will contain the body of the message
     */
    PdfPTable bodyTable = new PdfPTable(1);
    bodyTable.setWidthPercentage(100f);

    bodyTable.setSplitLate(false);

    bodyTable.setSpacingBefore(15f);
    bodyTable.setHorizontalAlignment(Element.ALIGN_LEFT);

    addBodyAndAttachments(pdfWriter, document, bodyTable, body, attachments);

    Phrase footer = new Phrase(FOOTER_TEXT);

    PdfContentByte cb = pdfWriter.getDirectContent();

    ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, footer, document.right(), document.bottom(), 0);

    document.close();
}

From source file:com.studiostorti.ZimbraFlowHandler.java

@Override
public void handleRequest(ZimbraContext zimbraContext, SoapResponse soapResponse,
        ZimbraExceptionContainer zimbraExceptionContainer) {
    String requesterId = zimbraContext.getAuthenticatedAccontId();
    Mailbox mailbox = mMailboxManager.getMailboxByAccountId(requesterId);
    Account account = mProvisioning.getAccountById(requesterId);
    Map<String, String> args = new HashMap<String, String>();

    if (account == null) {
        soapResponse.setValue("reply", "KONon e' stato possibile trovare l'account : " + requesterId);

        return;//from  www  . j  ava2  s .  com
    }

    OperationContext octxt = new OperationContext(account);
    String msgId = zimbraContext.getParameter("id", "");
    String namespace = zimbraContext.getParameter("namespace", "");
    String url = zimbraContext.getParameter("url", "");
    String user = account.getName();
    ZimbraLog.extensions
            .info("Azione ZimbraFlow richiesta da '" + user + "' per il messaggio: '" + msgId + "'");
    args.put("cUserEmail", user);

    Message item;
    if (!msgId.contains(":")) {
        try {
            item = mailbox.getMessageById(octxt, Integer.parseInt(msgId));
        } catch (Exception e) {
            soapResponse.setValue("reply",
                    "KONon e' stato possibile recuperare il messaggio (" + msgId + "): " + e.getMessage());

            return;
        }

        ZimbraLog.mailbox.info("ZimbraFlow mail id : " + msgId);
        args.put("cEmailUniqueID", account.getId() + ":" + msgId);
    } else {
        ZimbraLog.mailbox.info("ZimbraFlow il messaggio e' una cartella condivisa");
        String accountId = msgId.substring(0, msgId.indexOf(':'));
        String itemId = msgId.substring(msgId.indexOf(':') + 1);

        try {
            Mailbox ownerMailbox = mMailboxManager.getMailboxByAccountId(accountId);
            item = ownerMailbox.getMessageById(octxt, Integer.parseInt(itemId));
        } catch (Exception e) {
            soapResponse.setValue("reply",
                    "KONon e' stato possibile recuperare il messaggio (" + msgId + "): " + e.getMessage());

            return;
        }

        args.put("cEmailUniqueID", msgId);
    }
    if (item == null) {
        soapResponse.setValue("reply", "KONon e' stato possibile recuperare il messaggio (" + msgId + ".");

        return;
    }

    MimeMessage mimeMessage = null;
    try {
        mimeMessage = item.getMimeMessage();
        args.put("cEmailMessageID", mimeMessage.getMessageID());
    } catch (MessagingException e) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cEmailMessageID: " + e.getMessage());
    }

    byte[] mime = item.getContent();

    args.put("StreamBase64", Base64.encodeBase64String(mime));

    String subject;
    subject = item.getSubject();
    args.put("cSubject", subject);

    String body;
    try {
        body = getText(mimeMessage);
    } catch (MessagingException e) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cBody: " + e.getMessage());
        body = "";
    } catch (IOException e) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cBody: " + e.getMessage());
        body = "";
    }
    args.put("cBody", body);

    try {
        Address from = mimeMessage.getFrom()[0];
        args.put("cFrom", ((InternetAddress) from).getAddress());
    } catch (NullPointerException ne) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cFrom: " + ne.getMessage());
        args.put("cFrom", "");
    } catch (MessagingException e) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cFrom: " + e.getMessage());
        args.put("cFrom", "");
    }

    try {
        Address[] toRecipients = mimeMessage.getRecipients(javax.mail.Message.RecipientType.TO);
        String toString = "";
        for (Address to : toRecipients) {
            toString += ((InternetAddress) to).getAddress() + ",";
        }
        if (toString.length() > 0)
            args.put("cTO", toString.substring(0, toString.length() - 1));
        else
            args.put("cTO", toString);
    } catch (MessagingException ignored) {
    } catch (NullPointerException ne) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cTo: " + ne.getMessage());
        args.put("cTO", "");
    }

    try {
        Address[] ccRecipients = mimeMessage.getRecipients(javax.mail.Message.RecipientType.CC);
        String ccString = "";
        if (ccRecipients != null) {
            for (Address cc : ccRecipients) {
                ccString += ((InternetAddress) cc).getAddress() + ",";
            }
        }
        if (ccString.length() > 0)
            args.put("cCC", ccString.substring(0, ccString.length() - 1));
        else
            args.put("cCC", ccString);
    } catch (MessagingException ignored) {
    } catch (NullPointerException ne) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cCC: " + ne.getMessage());
        args.put("cCC", "");
    }

    try {
        Address[] bccRecipients = mimeMessage.getRecipients(javax.mail.Message.RecipientType.BCC);
        String bccString = "";
        if (bccRecipients != null) {
            for (Address bcc : bccRecipients) {
                bccString += ((InternetAddress) bcc).getAddress() + ",";
            }
        }
        if (bccString.length() > 0)
            args.put("cCCN", bccString.substring(0, bccString.length() - 1));
        else
            args.put("cCCN", bccString);

    } catch (MessagingException ignored) {
    } catch (NullPointerException ne) {
        ZimbraLog.mailbox.warn("ZimbraFlow errore cCCN: " + ne.getMessage());
        args.put("cCCN", "");
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
    long date = item.getDate();
    args.put("cDateTime", dateFormat.format(new Date(date)));

    if (args.get("cDateTime") == null || args.get("cUserEmail") == null || args.get("StreamBase64") == null) {
        String message = "KONon sono stati trovati tutti i campi obbligatori:";
        if (args.get("cDateTime") == null)
            message += "\nManca il campo cDateTime";
        else if (args.get("cUserEmail") == null)
            message += "\nManca  il campo cUserEmail";
        else if (args.get("StreamBase64") == null)
            message += "\nManca il campo StreamBase64";

        soapResponse.setValue("reply", message);

        return;
    }

    SOAPClient soapClient = new SOAPClient(url, namespace);
    try {
        String res = soapClient.sendRequest(args);
        soapResponse.setValue("reply", res);
    } catch (SOAPException e) {
        ZimbraLog.mailbox.error("ZimbraFlow SOAP call exception: " + e.getMessage());
        soapResponse.setValue("reply", "KO" + e.getMessage());
    }
}

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 ava 2s .  c om
//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) {//from   ww  w .j a  va 2s .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;
}