Example usage for javax.mail.internet MimeMessage getContentType

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

Introduction

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

Prototype

@Override
public String getContentType() throws MessagingException 

Source Link

Document

Returns the value of the RFC 822 "Content-Type" header field.

Usage

From source file:davmail.exchange.ews.EwsExchangeSession.java

@Override
public void sendMessage(MimeMessage mimeMessage) throws IOException, MessagingException {
    String itemClass = null;//from   www  .j  av  a  2 s .c o m
    if (mimeMessage.getContentType().startsWith("multipart/report")) {
        itemClass = "REPORT.IPM.Note.IPNRN";
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        mimeMessage.writeTo(baos);
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
    sendMessage(itemClass, baos.toByteArray());
}

From source file:immf.SendMailBridge.java

/**
 * SMTP???????//from  w ww.jav a 2 s  .  c o m
 * @param msg
 * @throws IOException
 */
public void receiveMail(MyWiserMessage msg) throws IOException {
    try {
        SenderMail senderMail = new SenderMail();

        log.info("==== SMTP???????====");
        log.info("From       " + msg.getEnvelopeSender());
        log.info("Recipients  " + msg.getEnvelopeReceiver());

        MimeMessage mime = msg.getMimeMessage();

        String messageId = mime.getHeader("Message-ID", null);
        log.info("messageID  " + messageId);
        List<String> recipients;
        if (messageId != null && receivedMessageTable != null) {
            synchronized (receivedMessageTable) {
                recipients = receivedMessageTable.get(messageId);
                if (recipients != null) {
                    recipients.addAll(msg.getEnvelopeReceiver());
                    log.info("Duplicated message ignored");
                    return;
                }

                recipients = msg.getEnvelopeReceiver();
                receivedMessageTable.put(messageId, recipients);
                receivedMessageTable.wait(this.duplicationCheckTimeSec * 1000);
                receivedMessageTable.remove(messageId);
            }
        } else {
            recipients = msg.getEnvelopeReceiver();
        }

        List<InternetAddress> to = getRecipients(mime, "To");
        List<InternetAddress> cc = getRecipients(mime, "Cc");
        List<InternetAddress> bcc = getBccRecipients(recipients, to, cc);

        int maxRecipients = MaxRecipient;
        if (this.alwaysBcc != null) {
            log.debug("add alwaysbcc " + this.alwaysBcc);
            bcc.add(new InternetAddress(this.alwaysBcc));
        }
        log.info("To   " + StringUtils.join(to, " / "));
        log.info("cc   " + StringUtils.join(cc, " / "));
        log.info("bcc   " + StringUtils.join(bcc, " / "));

        senderMail.setTo(to);
        senderMail.setCc(cc);
        senderMail.setBcc(bcc);

        if (maxRecipients < (to.size() + cc.size() + bcc.size())) {
            log.warn("??????i.net???5??");
            throw new IOException("Too Much Recipients");
        }

        String contentType = mime.getContentType().toLowerCase();
        log.info("ContentType:" + contentType);

        String charset = (new ContentType(contentType)).getParameter("charset");
        log.info("charset:" + charset);

        String mailer = mime.getHeader("X-Mailer", null);
        log.info("mailer  " + mailer);

        String subject = mime.getHeader("Subject", null);
        log.info("subject  " + subject);
        if (subject != null)
            subject = this.charConv.convertSubject(subject);
        log.debug(" conv " + subject);

        if (this.useGoomojiSubject) {
            String goomojiSubject = mime.getHeader("X-Goomoji-Subject", null);
            if (goomojiSubject != null)
                subject = this.googleCharConv.convertSubject(goomojiSubject);
        }

        boolean editRe = false;
        if (this.editDocomoSubjectPrefix) {
            for (InternetAddress addr : to) {
                String[] toString = addr.getAddress().split("@", 2);
                if (subject != null && toString[1].equals("docomo.ne.jp")) {
                    editRe = true;
                }
            }
        }
        if (editRe) {
            if (subject.matches("^R[eE]: ?R[eE].*$")) {
                log.info("?subject: " + subject);
                String reCounterStr = subject.replaceAll("^R[eE]: ?R[eE](\\d*):.*$", "$1");
                int reCounter = 2;
                if (!reCounterStr.isEmpty()) {
                    reCounter = Integer.parseInt(reCounterStr);
                    reCounter++;
                }
                subject = subject.replaceAll("^R[eE]: ?R[eE]\\d*:", "Re" + Integer.toString(reCounter) + ":");
                log.info("subject: " + subject);
            }
        }

        senderMail.setSubject(subject);

        Object content = mime.getContent();
        if (content instanceof String) {
            // 
            String strContent = (String) content;
            if (contentType.toLowerCase().startsWith("text/html")) {
                log.info("Single html part " + strContent);
                strContent = this.charConv.convert(strContent, charset);
                log.debug(" conv " + strContent);
                senderMail.setHtmlContent(strContent);
            } else {
                log.info("Single plainText part " + strContent);
                strContent = this.charConv.convert(strContent, charset);
                log.debug(" conv " + strContent);
                senderMail.setPlainTextContent(strContent);
            }
        } else if (content instanceof Multipart) {
            Multipart mp = (Multipart) content;
            parseMultipart(senderMail, mp, getSubtype(contentType), null);
            if (senderMail.getHtmlContent() == null && senderMail.getHtmlWorkingContent() != null) {
                senderMail.setHtmlContent(senderMail.getHtmlWorkingContent());
            }

        } else {
            log.warn("? " + content.getClass().getName());
            throw new IOException("Unsupported type " + content.getClass().getName() + ".");
        }

        if (stripAppleQuote) {
            Util.stripAppleQuotedLines(senderMail);
        }
        Util.stripLastEmptyLines(senderMail);

        log.info("Content  " + mime.getContent());
        log.info("====");

        if (this.sendAsync) {
            // ??
            // ?????OK?
            this.picker.add(senderMail);
        } else {
            // ??????
            this.client.sendMail(senderMail, this.forcePlainText);
            if (isForwardSent) {
                status.setNeedConnect();
            }
        }

    } catch (IOException e) {
        log.warn("Bad Mail Received.", e);
        throw e;
    } catch (Exception e) {
        log.error("ReceiveMail Error.", e);
        throw new IOException("ReceiveMail Error." + e.getMessage(), e);
    }
}

From source file:eu.peppol.outbound.transmission.As2MessageSender.java

SendResult send(InputStream inputStream, ParticipantId recipient, ParticipantId sender,
        PeppolDocumentTypeId peppolDocumentTypeId, SmpLookupManager.PeppolEndpointData peppolEndpointData,
        PeppolAs2SystemIdentifier as2SystemIdentifierOfSender) {

    if (peppolEndpointData.getCommonName() == null) {
        throw new IllegalArgumentException("No common name in EndPoint object. " + peppolEndpointData);
    }/*from w w w  .j  a v  a2  s.  c o  m*/
    X509Certificate ourCertificate = keystoreManager.getOurCertificate();

    SMimeMessageFactory sMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(),
            ourCertificate);
    MimeMessage signedMimeMessage = null;
    Mic mic = null;
    try {
        MimeBodyPart mimeBodyPart = MimeMessageHelper.createMimeBodyPart(inputStream,
                new MimeType("application/xml"));
        mic = MimeMessageHelper.calculateMic(mimeBodyPart);
        log.debug("Outbound MIC is : " + mic.toString());
        signedMimeMessage = sMimeMessageFactory.createSignedMimeMessage(mimeBodyPart);
    } catch (MimeTypeParseException e) {
        throw new IllegalStateException("Problems with MIME types: " + e.getMessage(), e);
    }

    String endpointAddress = peppolEndpointData.getUrl().toExternalForm();
    HttpPost httpPost = new HttpPost(endpointAddress);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        signedMimeMessage.writeTo(byteArrayOutputStream);

    } catch (Exception e) {
        throw new IllegalStateException("Unable to stream S/MIME message into byte array output stream");
    }

    httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), as2SystemIdentifierOfSender.toString());
    try {
        httpPost.setHeader(As2Header.AS2_TO.getHttpHeaderName(),
                PeppolAs2SystemIdentifier.valueOf(peppolEndpointData.getCommonName()).toString());
    } catch (InvalidAs2SystemIdentifierException e) {
        throw new IllegalArgumentException(
                "Unable to create valid AS2 System Identifier for receiving end point: " + peppolEndpointData);
    }

    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_TO.getHttpHeaderName(), "not.in.use@difi.no");
    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(),
            As2DispositionNotificationOptions.getDefault().toString());
    httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION);
    httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 message from OXALIS");

    TransmissionId transmissionId = new TransmissionId();
    httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), transmissionId.toString());
    httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date()));

    // Inserts the S/MIME message to be posted.
    // Make sure we pass the same content type as the SignedMimeMessage, it'll end up as content-type HTTP header
    try {
        String contentType = signedMimeMessage.getContentType();
        ContentType ct = ContentType.create(contentType);
        httpPost.setEntity(new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ct));
    } catch (Exception ex) {
        throw new IllegalStateException("Unable to set request header content type : " + ex.getMessage());
    }

    CloseableHttpResponse postResponse = null; // EXECUTE !!!!
    try {
        CloseableHttpClient httpClient = createCloseableHttpClient();
        log.debug("Sending AS2 from " + sender + " to " + recipient + " at " + endpointAddress + " type "
                + peppolDocumentTypeId);
        postResponse = httpClient.execute(httpPost);
    } catch (HttpHostConnectException e) {
        throw new IllegalStateException("The Oxalis server does not seem to be running at " + endpointAddress);
    } catch (Exception e) {
        throw new IllegalStateException(
                "Unexpected error during execution of http POST to " + endpointAddress + ": " + e.getMessage(),
                e);
    }

    if (postResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        log.error("AS2 HTTP POST expected HTTP OK, but got : " + postResponse.getStatusLine().getStatusCode()
                + " from " + endpointAddress);
        throw handleFailedRequest(postResponse);
    }

    // handle normal HTTP OK response
    log.debug("AS2 transmission " + transmissionId + " to " + endpointAddress
            + " returned HTTP OK, verify MDN response");
    MimeMessage mimeMessage = handleTheHttpResponse(transmissionId, mic, postResponse, peppolEndpointData);

    // Transforms the signed MDN into a generic a As2RemWithMdnTransmissionEvidenceImpl
    MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
    Map<String, String> mdnFields = mdnMimeMessageInspector.getMdnFields();
    String messageDigestAsBase64 = mdnFields.get(MdnMimeMessageFactory.X_ORIGINAL_MESSAGE_DIGEST);
    if (messageDigestAsBase64 == null) {
        messageDigestAsBase64 = new String(Base64.getEncoder().encode("null".getBytes()));
    }
    String receptionTimeStampAsString = mdnFields.get(MdnMimeMessageFactory.X_PEPPOL_TIME_STAMP);
    Date receptionTimeStamp = null;
    if (receptionTimeStampAsString != null) {
        receptionTimeStamp = As2DateUtil.parseIso8601TimeStamp(receptionTimeStampAsString);
    } else {
        receptionTimeStamp = new Date();
    }

    // Converts the Oxalis DocumentTypeIdentifier into the corresponding type for peppol-evidence
    DocumentTypeIdentifier documentTypeIdentifier = new DocumentTypeIdentifier(peppolDocumentTypeId.toString());

    @NotNull
    As2RemWithMdnTransmissionEvidenceImpl evidence = as2TransmissionEvidenceFactory.createEvidence(
            EventCode.DELIVERY, TransmissionRole.C_2, mimeMessage,
            new ParticipantIdentifier(recipient.stringValue()), // peppol-evidence uses it's own types
            new ParticipantIdentifier(sender.stringValue()), // peppol-evidence uses it's own types
            documentTypeIdentifier, receptionTimeStamp, Base64.getDecoder().decode(messageDigestAsBase64),
            transmissionId);

    ByteArrayOutputStream evidenceBytes;
    try {
        evidenceBytes = new ByteArrayOutputStream();
        IOUtils.copy(evidence.getInputStream(), evidenceBytes);
    } catch (IOException e) {
        throw new IllegalStateException(
                "Unable to transform transport evidence to byte array." + e.getMessage(), e);
    }

    return new SendResult(transmissionId, evidenceBytes.toByteArray());
}

From source file:davmail.exchange.dav.DavExchangeSession.java

@Override
public void sendMessage(MimeMessage mimeMessage) throws IOException {
    try {//from w w  w  . j a va  2  s .  c o m
        // need to create draft first
        String itemName = UUID.randomUUID().toString() + ".EML";
        HashMap<String, String> properties = new HashMap<String, String>();
        properties.put("draft", "9");
        String contentType = mimeMessage.getContentType();
        if (contentType != null && contentType.startsWith("text/plain")) {
            properties.put("messageFormat", "1");
        } else {
            properties.put("mailOverrideFormat",
                    String.valueOf(ENCODING_PREFERENCE | ENCODING_MIME | BODY_ENCODING_TEXT_AND_HTML));
            properties.put("messageFormat", "2");
        }
        createMessage(DRAFTS, itemName, properties, mimeMessage);
        MoveMethod method = new MoveMethod(URIUtil.encodePath(getFolderPath(DRAFTS + '/' + itemName)),
                URIUtil.encodePath(getFolderPath(SENDMSG)), false);
        // set header if saveInSent is disabled 
        if (!Settings.getBooleanProperty("davmail.smtpSaveInSent", true)) {
            method.setRequestHeader("Saveinsent", "f");
        }
        moveItem(method);
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:com.zimbra.cs.service.mail.ToXML.java

/** Encodes a Message object into <m> element with <mp> elements for
 *  message body./*w  w  w .  j  a  v a2s.co m*/
 * @param parent  The Element to add the new <tt>&lt;m></tt> to.
 * @param ifmt    The formatter to sue when serializing item ids.
 * @param msg     The Message to serialize.
 * @param part    If non-null, serialize this message/rfc822 subpart of
 *                the Message instead of the Message itself.
 * @param maxSize TODO
 * @param wantHTML  <tt>true</tt> to prefer HTML parts as the "body",
 *                  <tt>false</tt> to prefer text/plain parts.
 * @param neuter  Whether to rename "src" attributes on HTML <img> tags.
 * @param headers Extra message headers to include in the returned element.
 * @param serializeType If <tt>false</tt>, always serializes as an
 *                      <tt>&lt;m></tt> element.
 * @param bestEffort  If <tt>true</tt>, errors serializing part content
 *                    are swallowed.
 * @return The newly-created <tt>&lt;m></tt> Element, which has already
 *         been added as a child to the passed-in <tt>parent</tt>.
 * @throws ServiceException */
private static Element encodeMessageAsMP(Element parent, ItemIdFormatter ifmt, OperationContext octxt,
        Message msg, String part, int maxSize, boolean wantHTML, boolean neuter, Set<String> headers,
        boolean serializeType, boolean wantExpandGroupInfo, boolean bestEffort, boolean encodeMissingBlobs,
        MsgContent wantContent) throws ServiceException {
    Element m = null;
    boolean success = false;
    try {
        boolean wholeMessage = part == null || part.trim().isEmpty();
        if (wholeMessage) {
            m = encodeMessageCommon(parent, ifmt, octxt, msg, NOTIFY_FIELDS, serializeType);
            m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(msg));
        } else {
            m = parent.addElement(MailConstants.E_MSG);
            m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(msg));
            m.addAttribute(MailConstants.A_PART, part);
        }

        MimeMessage mm = null;
        try {
            String requestedAccountId = octxt.getmRequestedAccountId();
            String authtokenAccountId = octxt.getmAuthTokenAccountId();
            boolean isDecryptionNotAllowed = StringUtils.isNotEmpty(authtokenAccountId)
                    && !authtokenAccountId.equalsIgnoreCase(requestedAccountId);
            if (isDecryptionNotAllowed && Mime.isEncrypted(msg.getMimeMessage(false).getContentType())) {
                mm = msg.getMimeMessage(false);
            } else {
                mm = msg.getMimeMessage();
            }
        } catch (MailServiceException e) {
            if (encodeMissingBlobs && MailServiceException.NO_SUCH_BLOB.equals(e.getCode())) {
                ZimbraLog.mailbox.error("Unable to get blob while encoding message", e);
                encodeEmail(m, msg.getSender(), EmailType.FROM);
                encodeEmail(m, msg.getSender(), EmailType.SENDER);
                if (msg.getRecipients() != null) {
                    addEmails(m, Mime.parseAddressHeader(msg.getRecipients()), EmailType.TO);
                }
                m.addAttribute(MailConstants.A_SUBJECT, msg.getSubject());
                Element mimePart = m.addElement(MailConstants.E_MIMEPART);
                mimePart.addAttribute(MailConstants.A_PART, 1);
                mimePart.addAttribute(MailConstants.A_BODY, true);
                mimePart.addAttribute(MailConstants.A_CONTENT_TYPE, MimeConstants.CT_TEXT_PLAIN);

                String errMsg = L10nUtil.getMessage(L10nUtil.MsgKey.errMissingBlob,
                        msg.getAccount().getLocale(), ifmt.formatItemId(msg));
                m.addAttribute(MailConstants.E_FRAG, errMsg, Element.Disposition.CONTENT);
                mimePart.addAttribute(MailConstants.E_CONTENT, errMsg, Element.Disposition.CONTENT);
                success = true; //not really success, but mark as such so the element is appended correctly
                return m;
            }
            throw e;
        }
        if (!wholeMessage) {
            MimePart mp = Mime.getMimePart(mm, part);
            if (mp == null) {
                throw MailServiceException.NO_SUCH_PART(part);
            }
            Object content = Mime.getMessageContent(mp);
            if (!(content instanceof MimeMessage)) {
                throw MailServiceException.NO_SUCH_PART(part);
            }
            mm = (MimeMessage) content;
        } else {
            part = "";
        }

        // Add fragment before emails to maintain consistent ordering
        // of elements with encodeConversation - need to do this to
        // overcome JAXB issues.

        String fragment = msg.getFragment();
        if (fragment != null && !fragment.isEmpty()) {
            m.addAttribute(MailConstants.E_FRAG, fragment, Element.Disposition.CONTENT);
        }

        addEmails(m, Mime.parseAddressHeader(mm, "From"), EmailType.FROM);
        addEmails(m, Mime.parseAddressHeader(mm, "Sender"), EmailType.SENDER);
        addEmails(m, Mime.parseAddressHeader(mm, "Reply-To"), EmailType.REPLY_TO);
        addEmails(m, Mime.parseAddressHeader(mm, "To"), EmailType.TO);
        addEmails(m, Mime.parseAddressHeader(mm, "Cc"), EmailType.CC);
        addEmails(m, Mime.parseAddressHeader(mm, "Bcc"), EmailType.BCC);
        addEmails(m, Mime.parseAddressHeader(mm.getHeader("Resent-From", null), false), EmailType.RESENT_FROM);
        // read-receipts only get sent by the mailbox's owner
        if (!(octxt.isDelegatedRequest(msg.getMailbox()) && octxt.isOnBehalfOfRequest(msg.getMailbox()))) {
            addEmails(m, Mime.parseAddressHeader(mm, "Disposition-Notification-To"), EmailType.READ_RECEIPT);
        }

        String calIntendedFor = msg.getCalendarIntendedFor();
        m.addAttribute(MailConstants.A_CAL_INTENDED_FOR, calIntendedFor);

        String subject = Mime.getSubject(mm);
        if (subject != null) {
            m.addAttribute(MailConstants.E_SUBJECT, StringUtil.stripControlCharacters(subject),
                    Element.Disposition.CONTENT);
        }

        String messageID = mm.getMessageID();
        if (messageID != null && !messageID.trim().isEmpty()) {
            m.addAttribute(MailConstants.E_MSG_ID_HDR, StringUtil.stripControlCharacters(messageID),
                    Element.Disposition.CONTENT);
        }

        if (wholeMessage && msg.isDraft()) {
            if (!msg.getDraftOrigId().isEmpty()) {
                ItemId origId = new ItemId(msg.getDraftOrigId(), msg.getMailbox().getAccountId());
                m.addAttribute(MailConstants.A_ORIG_ID, ifmt.formatItemId(origId));
            }
            if (!msg.getDraftReplyType().isEmpty()) {
                m.addAttribute(MailConstants.A_REPLY_TYPE, msg.getDraftReplyType());
            }
            if (!msg.getDraftIdentityId().isEmpty()) {
                m.addAttribute(MailConstants.A_IDENTITY_ID, msg.getDraftIdentityId());
            }
            if (!msg.getDraftAccountId().isEmpty()) {
                m.addAttribute(MailConstants.A_FOR_ACCOUNT, msg.getDraftAccountId());
            }
            String inReplyTo = mm.getHeader("In-Reply-To", null);
            if (inReplyTo != null && !inReplyTo.isEmpty()) {
                m.addAttribute(MailConstants.E_IN_REPLY_TO, StringUtil.stripControlCharacters(inReplyTo),
                        Element.Disposition.CONTENT);
            }
            if (msg.getDraftAutoSendTime() != 0) {
                m.addAttribute(MailConstants.A_AUTO_SEND_TIME, msg.getDraftAutoSendTime());
            }
        }

        if (!wholeMessage) {
            m.addAttribute(MailConstants.A_SIZE, mm.getSize());
        }

        Date sent = mm.getSentDate();
        if (sent != null) {
            m.addAttribute(MailConstants.A_SENT_DATE, sent.getTime());
        }

        Calendar resent = DateUtil.parseRFC2822DateAsCalendar(mm.getHeader("Resent-Date", null));
        if (resent != null) {
            m.addAttribute(MailConstants.A_RESENT_DATE, resent.getTimeInMillis());
        }

        if (msg.isInvite() && msg.hasCalendarItemInfos()) {
            encodeInvitesForMessage(m, ifmt, octxt, msg, NOTIFY_FIELDS, neuter);
        }

        if (headers != null) {
            for (String name : headers) {
                String[] values = mm.getHeader(name);
                if (values != null) {
                    for (int i = 0; i < values.length; i++) {
                        m.addKeyValuePair(name, values[i], MailConstants.A_HEADER,
                                MailConstants.A_ATTRIBUTE_NAME);
                    }
                }
            }
        }

        List<MPartInfo> parts = Mime.getParts(mm, getDefaultCharset(msg));
        if (parts != null && !parts.isEmpty()) {
            Set<MPartInfo> bodies = Mime.getBody(parts, wantHTML);
            addParts(m, parts.get(0), bodies, part, maxSize, neuter, false, getDefaultCharset(msg), bestEffort,
                    wantContent);
        }

        if (wantExpandGroupInfo) {
            ZimbraLog.gal.trace("want expand group info");
            Account authedAcct = octxt.getAuthenticatedUser();
            Account requestedAcct = msg.getMailbox().getAccount();
            encodeAddrsWithGroupInfo(m, requestedAcct, authedAcct);
        } else {
            ZimbraLog.gal.trace("do not want expand group info");
        }

        success = true;
        // update crypto flags - isSigned/isEncrypted
        if (SmimeHandler.getHandler() != null) {
            if (!wholeMessage) {
                // check content type of attachment message for encryption flag
                SmimeHandler.getHandler().updateCryptoFlags(msg, m, mm, mm);
            } else {
                MimeMessage originalMimeMessage = msg.getMimeMessage(false);
                SmimeHandler.getHandler().updateCryptoFlags(msg, m, originalMimeMessage, mm);
            }
        }

        // if the mime it is signed
        if (Mime.isMultipartSigned(mm.getContentType()) || Mime.isPKCS7Signed(mm.getContentType())) {
            ZimbraLog.mailbox
                    .debug("The message is signed. Forwarding it to SmimeHandler for signature verification.");
            if (SmimeHandler.getHandler() != null) {
                SmimeHandler.getHandler().verifyMessageSignature(msg.getMailbox().getAccount(), m, mm,
                        octxt.getmResponseProtocol());
            }
        } else {
            // if the original mime message was PKCS7-signed and it was
            // decoded and stored in cache as plain mime
            if ((mm instanceof Mime.FixedMimeMessage) && ((Mime.FixedMimeMessage) mm).isPKCS7Signed()) {
                if (SmimeHandler.getHandler() != null) {
                    SmimeHandler.getHandler().addPKCS7SignedMessageSignatureDetails(
                            msg.getMailbox().getAccount(), m, mm, octxt.getmResponseProtocol());
                }
            }
        }
        return m;
    } catch (IOException ex) {
        throw ServiceException.FAILURE(ex.getMessage(), ex);
    } catch (MessagingException ex) {
        throw ServiceException.FAILURE(ex.getMessage(), ex);
    } finally {
        // don't leave turds around if we're going to retry
        if (!success && !bestEffort && m != null) {
            m.detach();
        }
    }
}

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

public static String extractInfoMessage(MimeMessage message, Element root, VitamArgument argument,
        ConfigLoader config) {/*from www  . j  ava2s  .c o m*/
    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./*from   w w w.j av a  2  s  .  c om*/
 * 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.apache.axis.transport.mail.MailSender.java

/**
 * Read from server using POP3/*from   ww w . j  a v  a 2  s.  c o  m*/
 * @param msgContext
 * @throws Exception
 */
private void readUsingPOP3(String id, MessageContext msgContext) throws Exception {
    // Read the response back from the server
    String pop3Host = msgContext.getStrProp(MailConstants.POP3_HOST);
    String pop3User = msgContext.getStrProp(MailConstants.POP3_USERID);
    String pop3passwd = msgContext.getStrProp(MailConstants.POP3_PASSWORD);

    Reader reader;
    POP3MessageInfo[] messages = null;

    MimeMessage mimeMsg = null;
    POP3Client pop3 = new POP3Client();
    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    for (int i = 0; i < 12; i++) {
        pop3.connect(pop3Host);

        if (!pop3.login(pop3User, pop3passwd)) {
            pop3.disconnect();
            AxisFault fault = new AxisFault("POP3", "( Could not login to server.  Check password. )", null,
                    null);
            throw fault;
        }

        messages = pop3.listMessages();
        if (messages != null && messages.length > 0) {
            StringBuffer buffer = null;
            for (int j = 0; j < messages.length; j++) {
                reader = pop3.retrieveMessage(messages[j].number);
                if (reader == null) {
                    AxisFault fault = new AxisFault("POP3", "( Could not retrieve message header. )", null,
                            null);
                    throw fault;
                }

                buffer = new StringBuffer();
                BufferedReader bufferedReader = new BufferedReader(reader);
                int ch;
                while ((ch = bufferedReader.read()) != -1) {
                    buffer.append((char) ch);
                }
                bufferedReader.close();
                if (buffer.toString().indexOf(id) != -1) {
                    ByteArrayInputStream bais = new ByteArrayInputStream(buffer.toString().getBytes());
                    Properties prop = new Properties();
                    Session session = Session.getDefaultInstance(prop, null);

                    mimeMsg = new MimeMessage(session, bais);
                    pop3.deleteMessage(messages[j].number);
                    break;
                }
                buffer = null;
            }
        }
        pop3.logout();
        pop3.disconnect();
        if (mimeMsg == null) {
            Thread.sleep(5000);
        } else {
            break;
        }
    }

    if (mimeMsg == null) {
        pop3.logout();
        pop3.disconnect();
        AxisFault fault = new AxisFault("POP3", "( Could not retrieve message list. )", null, null);
        throw fault;
    }

    String contentType = mimeMsg.getContentType();
    String contentLocation = mimeMsg.getContentID();
    Message outMsg = new Message(mimeMsg.getInputStream(), false, contentType, contentLocation);

    outMsg.setMessageType(Message.RESPONSE);
    msgContext.setResponseMessage(outMsg);
    if (log.isDebugEnabled()) {
        log.debug("\n" + Messages.getMessage("xmlRecd00"));
        log.debug("-----------------------------------------------");
        log.debug(outMsg.getSOAPPartAsString());
    }
}

From source file:org.apache.axis.transport.mail.MailWorker.java

/**
 * Read all mime headers, returning the value of Content-Length and
 * SOAPAction.// www  .j  a  v a  2s.  c  o  m
 * @param mimeMessage         InputStream to read from
 * @param contentType The content type.
 * @param contentLocation The content location
 * @param soapAction StringBuffer to return the soapAction into
 */
private void parseHeaders(MimeMessage mimeMessage, StringBuffer contentType, StringBuffer contentLocation,
        StringBuffer soapAction) throws Exception {
    contentType.append(mimeMessage.getContentType());
    contentLocation.append(mimeMessage.getContentID());
    String values[] = mimeMessage.getHeader(HTTPConstants.HEADER_SOAP_ACTION);
    if (values != null)
        soapAction.append(values[0]);
}

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 {/*www. ja  va2s .  co  m*/
        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);
        }
    }
}