Example usage for javax.mail.internet MimeMessage MimeMessage

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

Introduction

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

Prototype

protected MimeMessage(Folder folder, int msgnum) 

Source Link

Document

Constructs an empty MimeMessage object with the given Folder and message number.

Usage

From source file:gov.nih.nci.cacis.nav.SendEncryptedMail.java

private MimeMessage encryptMessage(MimeMessage message, Session session, Certificate cert)
        throws NoSuchAlgorithmException, NoSuchProviderException, SMIMEException, MessagingException,
        IOException {/*  ww w .  ja v a2s. c o m*/
    /* Create the encrypter */
    final SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();
    encrypter.addKeyTransRecipient((X509Certificate) cert);

    /* Encrypt the message */
    final MimeBodyPart encryptedPart = encrypter.generate(message, SMIMEEnvelopedGenerator.AES256_CBC,
            PROVIDER_TYPE);

    /*
     * Create a new MimeMessage that contains the encrypted and signed content
     */
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    encryptedPart.writeTo(out);

    final MimeMessage encryptedMessage = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray()));

    /* Set all original MIME headers in the encrypted message */
    final Enumeration headers = message.getAllHeaderLines();
    while (headers.hasMoreElements()) {
        final String headerLine = (String) headers.nextElement();
        /*
         * Make sure not to override any content-* headers from the original message
         */
        if (!Strings.toLowerCase(headerLine).startsWith("content-")) {
            encryptedMessage.addHeaderLine(headerLine);
        }
    }

    return encryptedMessage;
}

From source file:mitm.common.mail.BodyPartUtils.java

/**
 * Extracts the message from the RFC822 attachment.
 * @throws MessagingException // w  w  w  .  j a  v  a  2s.c  om
 * @throws IOException 
 */
public static MimeMessage extractFromRFC822(Part rfc822) throws IOException, MessagingException {
    if (!rfc822.isMimeType("message/rfc822")) {
        throw new MessagingException("Part is-not-a message/rfc822 but " + rfc822.getContentType());
    }

    return new MimeMessage(MailSession.getDefaultSession(), rfc822.getInputStream());
}

From source file:davmail.smtp.TestSmtp.java

public void testBrokenMessage() throws MessagingException, IOException, InterruptedException {
    MimeMessage mimeMessage = new MimeMessage(null, new FileInputStream("test.eml"));
    sendAndCheckMessage(mimeMessage);/*  www . jav a2s . c om*/
}

From source file:davmail.smtp.TestSmtp.java

public void testBrokenMessage2() throws MessagingException, IOException, InterruptedException {
    MimeMessage mimeMessage = new MimeMessage(null,
            new org.apache.commons.codec.binary.Base64InputStream(new FileInputStream("broken64.txt")));
    mimeMessage.addHeader("To", Settings.getProperty("davmail.to"));
    sendAndCheckMessage(mimeMessage);//from  w  w w.  j  a v  a  2 s  . c o m
}

From source file:com.niroshpg.android.gmail.CronHandlerServlet.java

/**
 * Get a Message and use it to create a MimeMessage.
 *
 * @param service Authorized Gmail API instance.
 * @param userId User's email address. The special value "me"
 * can be used to indicate the authenticated user.
 * @param messageId ID of Message to retrieve.
 * @return MimeMessage MimeMessage populated from retrieved Message.
 * @throws IOException/*from   w  ww  .j  a va2s.  com*/
 * @throws MessagingException
 */
public static MimeMessage getMimeMessage(Gmail service, String userId, String messageId)
        throws IOException, MessagingException {
    Message message = service.users().messages().get(userId, messageId).setFormat("raw").execute();

    byte[] emailBytes = Base64.decodeBase64(message.getRaw());

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));

    return email;
}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

private EmailMessage wrapMessage(Message msg, boolean populateContent, Session session)
        throws MessagingException, IOException, ScanException, PolicyException {

    // Prepare subject
    String subject = msg.getSubject();
    if (!StringUtils.isBlank(subject)) {
        AntiSamy as = new AntiSamy();
        CleanResults cr = as.scan(subject, policy);
        subject = cr.getCleanHTML();/*from  w w  w . jav a2s . co m*/
    }

    // Prepare content if requested
    EmailMessageContent msgContent = null; // default...
    if (populateContent) {
        // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
        try {
            msgContent = getMessageContent(msg.getContent(), msg.getContentType());
        } catch (MessagingException me) {
            // We are unable to read digitally-signed messages (perhaps
            // others?) in the API-standard way;  we have to use a work around.
            // See: http://www.oracle.com/technetwork/java/faq-135477.html#imapserverbug
            // Logging as DEBUG because this behavior is known & expected.
            log.debug("Difficulty reading a message (digitally signed?). Attempting workaround...");
            try {
                MimeMessage mm = (MimeMessage) msg;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                mm.writeTo(bos);
                bos.close();
                SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray());
                MimeMessage copy = new MimeMessage(session, bis);
                bis.close();
                msgContent = getMessageContent(copy.getContent(), copy.getContentType());
            } catch (Throwable t) {
                log.error("Failed to read message body", t);
                msgContent = new EmailMessageContent("UNABLE TO READ MESSAGE BODY: " + t.getMessage(), false);
            }
        }

        // Sanitize with AntiSamy
        String content = msgContent.getContentString();
        if (!StringUtils.isBlank(content)) {
            AntiSamy as = new AntiSamy();
            CleanResults cr = as.scan(content, policy);
            content = cr.getCleanHTML();
        }
        msgContent.setContentString(content);
    }

    int messageNumber = msg.getMessageNumber();

    // Prepare the UID if present
    String uid = null; // default
    if (msg.getFolder() instanceof UIDFolder) {
        uid = Long.toString(((UIDFolder) msg.getFolder()).getUID(msg));
    }

    Address[] addr = msg.getFrom();
    String sender = getFormattedAddresses(addr);
    Date sentDate = msg.getSentDate();

    boolean unread = !msg.isSet(Flag.SEEN);
    boolean answered = msg.isSet(Flag.ANSWERED);
    boolean deleted = msg.isSet(Flag.DELETED);
    // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
    boolean multipart = false; // sensible default;
    String contentType = null; // sensible default
    try {
        multipart = msg.getContentType().toLowerCase().startsWith(CONTENT_TYPE_ATTACHMENTS_PATTERN);
        contentType = msg.getContentType();
    } catch (MessagingException me) {
        // Message was digitally signed and we are unable to read it;
        // logging as DEBUG because this issue is known/expected, and
        // because the user's experience is in no way affected (at this point)
        log.debug("Message content unavailable (digitally signed?);  "
                + "message will appear in the preview table correctly, " + "but the body will not be viewable");
        log.trace(me.getMessage(), me);
    }
    String to = getTo(msg);
    String cc = getCc(msg);
    String bcc = getBcc(msg);
    return new EmailMessage(messageNumber, uid, sender, subject, sentDate, unread, answered, deleted, multipart,
            contentType, msgContent, to, cc, bcc);
}

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

@Override
public void serviceMail(final Mail mail) {
    try {//from  w  w w.  j  a v  a  2 s  . co m
        final MimeMessage sourceMessage = mail.getMessage();

        if (sourceMessage != null) {
            Messages messages = actionExecutor.executeTransaction(new DatabaseAction<Messages>() {
                @Override
                public Messages doAction(Session session) throws DatabaseException {
                    Session previousSession = sessionManager.getSession();

                    sessionManager.setSession(session);

                    try {
                        return handleMessageTransacted(mail);
                    } finally {
                        sessionManager.setSession(previousSession);
                    }
                }
            }, ACTION_RETRIES /* retry on a ConstraintViolationException */);

            if (messages != null) {
                try {
                    Collection<MimeSource> mimeSources = messages.getMimeSources();

                    /*
                     * Send all handled S/MIME message to the handledProcessor next processor 
                     */
                    for (MimeSource mimeSource : mimeSources) {
                        InputStream mimeInput = mimeSource.getMimeSource().getInputStream();

                        MimeMessage message = retainMessageID
                                ? new MimeMessageWithID(MailSession.getDefaultSession(), mimeInput,
                                        sourceMessage.getMessageID())
                                : new MimeMessage(MailSession.getDefaultSession(), mimeInput);

                        sendNewMessage(mail, mimeSource.getRecipients(), message, handledProcessor);
                    }

                    /*
                     * Send email to all the recipients that need the message unchanged
                     */
                    Set<MailAddress> asIsRecipients = messages.getAsIsRecipients();

                    if (CollectionUtils.isEmpty(asIsRecipients)) {
                        /*
                         * We no longer need the original Mail so ghost it
                         */
                        mail.setState(Mail.GHOST);
                    } else {
                        mail.setRecipients(asIsRecipients);
                    }
                } finally {
                    messages.close();
                }
            }
        }
    } catch (DatabaseException e) {
        getLogger().error("Error handling the message.", e);
    } catch (MessagingException e) {
        getLogger().error("Error handling the message.", e);
    } catch (IOException e) {
        getLogger().error("Error handling the message.", e);
    }
}

From source file:javamailclient.GmailAPI.java

public static MimeMessage getMimeMessage(String messageId) throws IOException, MessagingException {
    String userId = USER;//from   w ww  . j a v a2 s .  c  om
    Message message = service.users().messages().get(userId, messageId).setFormat("raw").execute();

    byte[] emailBytes = Base64.decodeBase64(message.getRaw());

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));
    //System.out.println(email.getContentType());
    return email;
}

From source file:javamailclient.GmailAPI.java

public static Map getMessageDetails(String messageId) throws IOException, MessagingException {
    Map<String, String> mapDetails = new HashMap<String, String>();
    Message message = service.users().messages().get("me", messageId).setFormat("raw").execute();
    byte[] bytes = Base64.decodeBase64(message.getRaw());

    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(bytes));
    mapDetails.put("subject", email.getSubject());
    String from = "None";
    if (email.getSender() != null) {
        from = email.getSender().toString();
    }/*from w  w  w.j  a  v  a 2s.c o m*/
    mapDetails.put("from", from);
    String date = "Unknown";
    if (email.getReceivedDate() != null) {
        date = email.getReceivedDate().toString();
    }
    mapDetails.put("receiveddate", date);
    date = "Unknown";
    if (email.getSentDate() != null) {
        date = email.getSentDate().toString();
    }
    mapDetails.put("senddate", date);
    mapDetails.put("body", getMessageBody(email));
    return mapDetails;
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Analyzes and creates passed message data
 *//*from   w  w  w.  j  ava2  s.com*/
public AS2Message createMessageFromRequest(byte[] rawMessageData, Properties header, String contentType)
        throws AS2Exception {
    AS2Message message = new AS2Message(new AS2MessageInfo());
    if (this.configConnection == null) {
        throw new AS2Exception(AS2Exception.PROCESSING_ERROR,
                "AS2MessageParser: Pass a DB connection before calling createMessageFromRequest()", message);
    }
    try {
        //decode the content transfer encoding if set
        rawMessageData = this.processContentTransferEncoding(rawMessageData, header);
        //check if this is a MDN
        MDNParser mdnParser = new MDNParser();
        AS2MDNInfo mdnInfo = mdnParser.parseMDNData(rawMessageData, contentType);
        //its a MDN
        if (mdnInfo != null) {
            message.setAS2Info(mdnInfo);
            mdnInfo.initializeByRequestHeader(header);
            return (this.createFromMDNRequest(rawMessageData, header, contentType, mdnInfo, mdnParser));
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            messageInfo.initializeByRequestHeader(header);
            //inbound AS2 message, no MDN
            //no futher processing if the message does not contain a message id
            if (messageInfo.getMessageId() == null) {
                return (message);
            }
            //figure out if the MDN should be signed NOW. If an error occurs beyond this point
            //the info has to know if the returned MDN should be signed
            messageInfo.getDispositionNotificationOptions()
                    .setHeaderValue(header.getProperty("disposition-notification-options"));
            //check for existing partners
            PartnerAccessDB partnerAccess = new PartnerAccessDB(this.configConnection, this.runtimeConnection);
            Partner sender = partnerAccess.getPartner(messageInfo.getSenderId());
            Partner receiver = partnerAccess.getPartner(messageInfo.getReceiverId());
            if (sender == null) {
                throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR,
                        "Sender AS2 id " + messageInfo.getSenderId() + " is unknown.", message);
            }
            if (receiver == null) {
                throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR,
                        "Receiver AS2 id " + messageInfo.getReceiverId() + " is unknown.", message);
            }
            if (!receiver.isLocalStation()) {
                throw new AS2Exception(
                        AS2Exception.PROCESSING_ERROR, "The receiver of the message ("
                                + receiver.getAS2Identification() + ") is not defined as a local station.",
                        message);
            }
            MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            //check if the message already exists
            AS2MessageInfo alreadyExistingInfo = this.messageAlreadyExists(messageAccess,
                    messageInfo.getMessageId());
            if (alreadyExistingInfo != null) {
                //perform notification: Resend detected, manual interaction might be required
                Notification notification = new Notification(this.configConnection, this.runtimeConnection);
                notification.sendResendDetected(messageInfo, alreadyExistingInfo, sender, receiver);
                throw new AS2Exception(AS2Exception.PROCESSING_ERROR, "An AS2 message with the message id "
                        + messageInfo.getMessageId()
                        + " has been already processed successfully by the system or is pending ("
                        + alreadyExistingInfo.getInitDate() + "). Please "
                        + " resubmit the message with a new message id instead or resending it if it should be processed again.",
                        new AS2Message(messageInfo));
            }
            messageAccess.initializeOrUpdateMessage(messageInfo);
            if (this.logger != null) {
                //do not log before because the logging process is related to an already created message in the transaction log
                this.logger.log(
                        Level.FINE, this.rb
                                .getResourceString("msg.incoming",
                                        new Object[] { messageInfo.getMessageId(),
                                                AS2Tools.getDataSizeDisplay(rawMessageData.length) }),
                        messageInfo);
            }
            //indicates if a sync or async mdn is requested
            messageInfo.setAsyncMDNURL(header.getProperty("receipt-delivery-option"));
            messageInfo.setRequestsSyncMDN(header.getProperty("receipt-delivery-option") == null
                    || header.getProperty("receipt-delivery-option").trim().length() == 0);
            message.setRawData(rawMessageData);
            byte[] decryptedData = this.decryptMessage(message, rawMessageData, contentType, sender, receiver);
            //may be already compressed here. Decompress first before going further
            if (this.contentTypeIndicatesCompression(contentType)) {
                byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(), decryptedData,
                        contentType);
                message.setDecryptedRawData(decompressed);
                //content type has changed now, get it from the decompressed data
                ByteArrayInputStream memIn = new ByteArrayInputStream(decompressed);
                MimeBodyPart tempPart = new MimeBodyPart(memIn);
                memIn.close();
                contentType = tempPart.getContentType();
            } else {
                //check the MIME structure that is embedded in decryptedData for its content type
                ByteArrayInputStream memIn = new ByteArrayInputStream(decryptedData);
                MimeMessage possibleCompressedPart = new MimeMessage(
                        Session.getInstance(System.getProperties()), memIn);
                memIn.close();
                if (this.contentTypeIndicatesCompression(possibleCompressedPart.getContentType())) {
                    long compressedSize = possibleCompressedPart.getSize();
                    byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(),
                            new SMIMECompressed(possibleCompressedPart), compressedSize);
                    message.setDecryptedRawData(decompressed);
                } else {
                    message.setDecryptedRawData(decryptedData);
                }
            }
            decryptedData = null;
            Part payloadPart = this.verifySignature(message, sender, contentType);
            //decompress the data if it has been sent compressed, only possible for signed data
            if (message.getAS2Info().getSignType() != AS2Message.SIGNATURE_NONE) {
                //signed message:
                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.1 MIC Calculation For Signed Message
                //For any signed message, the MIC to be returned is calculated over
                //the same data that was signed in the original message as per [AS1].
                //The signed content will be a mime bodypart that contains either
                //compressed or uncompressed data.                    
                this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType);
                payloadPart = this.decompressData(payloadPart, message);
                this.writePayloadsToMessage(payloadPart, message, header);
            } else {
                //this is an unsigned message
                this.writePayloadsToMessage(message.getDecryptedRawData(), message, header);
                //unsigned message:
                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.2 MIC Calculation For Encrypted, Unsigned Message
                //For encrypted, unsigned messages, the MIC to be returned is
                //calculated over the uncompressed data content including all
                //MIME header fields and any applied Content-Transfer-Encoding.

                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.3 MIC Calculation For Unencrypted, Unsigned Message
                //For unsigned, unencrypted messages, the MIC is calculated
                //over the uncompressed data content including all MIME header
                //fields and any applied Content-Transfer-Encoding.                    
                this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType);
            }
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("found.attachments",
                        new Object[] { messageInfo.getMessageId(), String.valueOf(message.getPayloadCount()) }),
                        messageInfo);
            }
            return (message);
        }
    } catch (Exception e) {
        if (e instanceof AS2Exception) {
            throw (AS2Exception) e;
        } else {
            throw new AS2Exception(AS2Exception.PROCESSING_ERROR, e.getMessage(), message);
        }
    }
}