Search in sources :

Example 76 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project zm-mailbox by Zimbra.

the class SpamExtract method writeAttachedMessages.

private static void writeAttachedMessages(MimeMessage mm, File outdir, String msgUri) throws IOException, MessagingException {
    // Not raw - ignore the spam report and extract messages that are in attachments...
    if (!(mm.getContent() instanceof MimeMultipart)) {
        LOG.warn("Spam/notspam messages must have attachments (skipping " + msgUri + ")");
        return;
    }
    MimeMultipart mmp = (MimeMultipart) mm.getContent();
    int nAttachments = mmp.getCount();
    boolean foundAtleastOneAttachedMessage = false;
    for (int i = 0; i < nAttachments; i++) {
        BodyPart bp = mmp.getBodyPart(i);
        if (!bp.isMimeType("message/rfc822")) {
            // Let's ignore all parts that are not messages.
            continue;
        }
        foundAtleastOneAttachedMessage = true;
        // the actual message
        Part msg = (Part) bp.getContent();
        File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++);
        OutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            if (msg instanceof MimeMessage) {
                //bug 74435 clone into newMsg so our parser has a chance to handle headers which choke javamail
                ZMimeMessage newMsg = new ZMimeMessage((MimeMessage) msg);
                newMsg.writeTo(os);
            } else {
                msg.writeTo(os);
            }
        } finally {
            os.close();
        }
        if (verbose)
            LOG.info("Wrote: " + file);
    }
    if (!foundAtleastOneAttachedMessage) {
        String msgid = mm.getHeader("Message-ID", " ");
        LOG.warn("message uri=" + msgUri + " message-id=" + msgid + " had no attachments");
    }
}
Also used : BodyPart(javax.mail.BodyPart) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) Part(javax.mail.Part) BodyPart(javax.mail.BodyPart) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 77 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project logging-log4j2 by apache.

the class SmtpManager method getMimeMultipart.

protected MimeMultipart getMimeMultipart(final byte[] encodedBytes, final InternetHeaders headers) throws MessagingException {
    final MimeMultipart mp = new MimeMultipart();
    final MimeBodyPart part = new MimeBodyPart(headers, encodedBytes);
    mp.addBodyPart(part);
    return mp;
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 78 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project jmeter by apache.

the class SendMailCommand method prepareMessage.

/**
     * Prepares message prior to be sent via execute()-method, i.e. sets
     * properties such as protocol, authentication, etc.
     *
     * @return Message-object to be sent to execute()-method
     * @throws MessagingException
     *             when problems constructing or sending the mail occur
     * @throws IOException
     *             when the mail content can not be read or truststore problems
     *             are detected
     */
public Message prepareMessage() throws MessagingException, IOException {
    Properties props = new Properties();
    String protocol = getProtocol();
    // set properties using JAF
    props.setProperty("mail." + protocol + ".host", smtpServer);
    props.setProperty("mail." + protocol + ".port", getPort());
    props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication));
    // set timeout
    props.setProperty("mail." + protocol + ".timeout", getTimeout());
    props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout());
    if (useStartTLS || useSSL) {
        try {
            String allProtocols = StringUtils.join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " ");
            logger.info("Use ssl/tls protocols for mail: " + allProtocols);
            props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols);
        } catch (Exception e) {
            logger.error("Problem setting ssl/tls protocols for mail", e);
        }
    }
    if (enableDebug) {
        props.setProperty("mail.debug", "true");
    }
    if (useStartTLS) {
        props.setProperty("mail.smtp.starttls.enable", "true");
        if (enforceStartTLS) {
            // Requires JavaMail 1.4.2+
            props.setProperty("mail.smtp.starttls.require", "true");
        }
    }
    if (trustAllCerts) {
        if (useSSL) {
            props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    } else if (useLocalTrustStore) {
        File truststore = new File(trustStoreToUse);
        logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
        if (!truststore.exists()) {
            logger.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
            truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse);
            logger.info("load local truststore -Attempting to read truststore from:  " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                logger.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution.");
                throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath());
            }
        }
        if (useSSL) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    }
    session = Session.getInstance(props, null);
    Message message;
    if (sendEmlMessage) {
        message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage)));
    } else {
        message = new MimeMessage(session);
        // handle body and attachments
        Multipart multipart = new MimeMultipart();
        final int attachmentCount = attachments.size();
        if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) {
            if (attachmentCount == 1) {
                // i.e. mailBody is empty
                File first = attachments.get(0);
                try (FileInputStream fis = new FileInputStream(first);
                    InputStream is = new BufferedInputStream(fis)) {
                    message.setText(IOUtils.toString(is, Charset.defaultCharset()));
                }
            } else {
                message.setText(mailBody);
            }
        } else {
            BodyPart body = new MimeBodyPart();
            body.setText(mailBody);
            multipart.addBodyPart(body);
            for (File f : attachments) {
                BodyPart attach = new MimeBodyPart();
                attach.setFileName(f.getName());
                attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath())));
                multipart.addBodyPart(attach);
            }
            message.setContent(multipart);
        }
    }
    // set from field and subject
    if (null != sender) {
        message.setFrom(new InternetAddress(sender));
    }
    if (null != replyTo) {
        InternetAddress[] to = new InternetAddress[replyTo.size()];
        message.setReplyTo(replyTo.toArray(to));
    }
    if (null != subject) {
        message.setSubject(subject);
    }
    if (receiverTo != null) {
        InternetAddress[] to = new InternetAddress[receiverTo.size()];
        receiverTo.toArray(to);
        message.setRecipients(Message.RecipientType.TO, to);
    }
    if (receiverCC != null) {
        InternetAddress[] cc = new InternetAddress[receiverCC.size()];
        receiverCC.toArray(cc);
        message.setRecipients(Message.RecipientType.CC, cc);
    }
    if (receiverBCC != null) {
        InternetAddress[] bcc = new InternetAddress[receiverBCC.size()];
        receiverBCC.toArray(bcc);
        message.setRecipients(Message.RecipientType.BCC, bcc);
    }
    for (int i = 0; i < headerFields.size(); i++) {
        Argument argument = (Argument) headerFields.get(i).getObjectValue();
        message.setHeader(argument.getName(), argument.getValue());
    }
    message.saveChanges();
    return message;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Argument(org.apache.jmeter.config.Argument) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) MimeMessage(javax.mail.internet.MimeMessage) BufferedInputStream(java.io.BufferedInputStream) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File)

Example 79 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project wildfly by wildfly.

the class JaxrsMultipartProviderTestCase method testJaxRsWithNoApplication.

@Test
public void testJaxRsWithNoApplication() throws Exception {
    String result = performCall("myjaxrs/form");
    DataSource mimeData = new ByteArrayDataSource(result.getBytes(), "multipart/related");
    MimeMultipart mime = new MimeMultipart(mimeData);
    String string = (String) mime.getBodyPart(0).getContent();
    Assert.assertEquals("Hello", string);
    string = (String) mime.getBodyPart(1).getContent();
    Assert.assertEquals("World", string);
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) Test(org.junit.Test)

Example 80 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project spring-framework by spring-projects.

the class MimeMessageHelper method createMimeMultiparts.

/**
	 * Determine the MimeMultipart objects to use, which will be used
	 * to store attachments on the one hand and text(s) and inline elements
	 * on the other hand.
	 * <p>Texts and inline elements can either be stored in the root element
	 * itself (MULTIPART_MODE_MIXED, MULTIPART_MODE_RELATED) or in a nested element
	 * rather than the root element directly (MULTIPART_MODE_MIXED_RELATED).
	 * <p>By default, the root MimeMultipart element will be of type "mixed"
	 * (MULTIPART_MODE_MIXED) or "related" (MULTIPART_MODE_RELATED).
	 * The main multipart element will either be added as nested element of
	 * type "related" (MULTIPART_MODE_MIXED_RELATED) or be identical to the root
	 * element itself (MULTIPART_MODE_MIXED, MULTIPART_MODE_RELATED).
	 * @param mimeMessage the MimeMessage object to add the root MimeMultipart
	 * object to
	 * @param multipartMode the multipart mode, as passed into the constructor
	 * (MIXED, RELATED, MIXED_RELATED, or NO)
	 * @throws MessagingException if multipart creation failed
	 * @see #setMimeMultiparts
	 * @see #MULTIPART_MODE_NO
	 * @see #MULTIPART_MODE_MIXED
	 * @see #MULTIPART_MODE_RELATED
	 * @see #MULTIPART_MODE_MIXED_RELATED
	 */
protected void createMimeMultiparts(MimeMessage mimeMessage, int multipartMode) throws MessagingException {
    switch(multipartMode) {
        case MULTIPART_MODE_NO:
            setMimeMultiparts(null, null);
            break;
        case MULTIPART_MODE_MIXED:
            MimeMultipart mixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED);
            mimeMessage.setContent(mixedMultipart);
            setMimeMultiparts(mixedMultipart, mixedMultipart);
            break;
        case MULTIPART_MODE_RELATED:
            MimeMultipart relatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED);
            mimeMessage.setContent(relatedMultipart);
            setMimeMultiparts(relatedMultipart, relatedMultipart);
            break;
        case MULTIPART_MODE_MIXED_RELATED:
            MimeMultipart rootMixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED);
            mimeMessage.setContent(rootMixedMultipart);
            MimeMultipart nestedRelatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED);
            MimeBodyPart relatedBodyPart = new MimeBodyPart();
            relatedBodyPart.setContent(nestedRelatedMultipart);
            rootMixedMultipart.addBodyPart(relatedBodyPart);
            setMimeMultiparts(rootMixedMultipart, nestedRelatedMultipart);
            break;
        default:
            throw new IllegalArgumentException("Only multipart modes MIXED_RELATED, RELATED and NO supported");
    }
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Aggregations

MimeMultipart (javax.mail.internet.MimeMultipart)213 MimeBodyPart (javax.mail.internet.MimeBodyPart)134 MimeMessage (javax.mail.internet.MimeMessage)85 MessagingException (javax.mail.MessagingException)69 ByteArrayOutputStream (java.io.ByteArrayOutputStream)55 BodyPart (javax.mail.BodyPart)55 IOException (java.io.IOException)47 ByteString (com.linkedin.data.ByteString)37 DataHandler (javax.activation.DataHandler)33 InternetAddress (javax.mail.internet.InternetAddress)33 Test (org.testng.annotations.Test)31 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)27 HashMap (java.util.HashMap)27 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)26 Multipart (javax.mail.Multipart)26 Properties (java.util.Properties)25 Session (javax.mail.Session)24 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)24 InputStream (java.io.InputStream)23 Date (java.util.Date)21