Search in sources :

Example 66 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart 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 67 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart 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 68 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project voldemort by voldemort.

the class CoordinatorRestAPITest method doGet.

private TestVersionedValue doGet(String key, Map<String, Object> options) {
    HttpURLConnection conn = null;
    String response = null;
    TestVersionedValue responseObj = null;
    int expectedResponseCode = 200;
    try {
        // Create the right URL and Http connection
        String base64Key = new String(Base64.encodeBase64(key.getBytes()));
        URL url = new URL(this.coordinatorURL + "/" + STORE_NAME + "/" + base64Key);
        conn = (HttpURLConnection) url.openConnection();
        // Set the right headers
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, "1000");
        conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS, Long.toString(System.currentTimeMillis()));
        // options
        if (options != null) {
            if (options.get("timeout") != null && options.get("timeout") instanceof String) {
                conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, (String) options.get("timeout"));
            }
            if (options.get("responseCode") != null && options.get("responseCode") instanceof Integer) {
                expectedResponseCode = (Integer) options.get("responseCode");
            }
        }
        // Check for the right response code
        if (conn.getResponseCode() != expectedResponseCode) {
            System.err.println("Illegal response during GET : " + conn.getResponseMessage());
            fail("Incorrect response received for a HTTP GET request :" + conn.getResponseCode());
        }
        if (conn.getResponseCode() == 404 || conn.getResponseCode() == 408) {
            return null;
        }
        // Buffer the result into a string
        ByteArrayDataSource ds = new ByteArrayDataSource(conn.getInputStream(), "multipart/mixed");
        MimeMultipart mp = new MimeMultipart(ds);
        assertEquals("The number of body parts expected is not 1", 1, mp.getCount());
        MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(0);
        VectorClock vc = RestUtils.deserializeVectorClock(part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]);
        int contentLength = Integer.parseInt(part.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]);
        byte[] bodyPartBytes = new byte[contentLength];
        part.getInputStream().read(bodyPartBytes);
        response = new String(bodyPartBytes);
        responseObj = new TestVersionedValue(response, vc);
    } catch (Exception e) {
        e.printStackTrace();
        fail("Error in sending the REST request");
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return responseObj;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) MimeMultipart(javax.mail.internet.MimeMultipart) VectorClock(voldemort.versioning.VectorClock) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) URL(java.net.URL)

Example 69 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project voldemort by voldemort.

the class GetAllResponseSender method sendResponse.

/**
     * Sends nested multipart response. Outer multipart wraps all the keys
     * requested. Each key has a separate multipart for the versioned values.
     */
@Override
public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception {
    /*
         * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.
         * However when writing to the outputStream we only send the multiPart object and not the entire
         * mimeMessage. This is intentional.
         *
         * In the earlier version of this code we used to create a multiPart object and just send that multiPart
         * across the wire.
         *
         * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates
         * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated
         * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the
         * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()
         * on the body part. It's this updateHeaders call that transfers the content type from the
         * DataHandler to the part's MIME Content-Type header.
         *
         * To make sure that the Content-Type headers are being updated (without changing too much code), we decided
         * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.
         * This is to make sure multiPart's headers are updated accurately.
         */
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    // multiPartKeys is the outer multipart
    MimeMultipart multiPartKeys = new MimeMultipart();
    ByteArrayOutputStream keysOutputStream = new ByteArrayOutputStream();
    for (Entry<ByteArray, List<Versioned<byte[]>>> entry : versionedResponses.entrySet()) {
        ByteArray key = entry.getKey();
        String base64Key = RestUtils.encodeVoldemortKey(key.get());
        String contentLocationKey = "/" + this.storeName + "/" + base64Key;
        // Create the individual body part - for each key requested
        MimeBodyPart keyBody = new MimeBodyPart();
        try {
            // Add the right headers
            keyBody.addHeader(CONTENT_TYPE, "application/octet-stream");
            keyBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
            keyBody.addHeader(CONTENT_LOCATION, contentLocationKey);
        } catch (MessagingException me) {
            logger.error("Exception while constructing key body headers", me);
            keysOutputStream.close();
            throw me;
        }
        // multiPartValues is the inner multipart
        MimeMultipart multiPartValues = new MimeMultipart();
        for (Versioned<byte[]> versionedValue : entry.getValue()) {
            byte[] responseValue = versionedValue.getValue();
            VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
            String eTag = RestUtils.getSerializedVectorClock(vectorClock);
            numVectorClockEntries += vectorClock.getVersionMap().size();
            // Create the individual body part - for each versioned value of
            // a key
            MimeBodyPart valueBody = new MimeBodyPart();
            try {
                // Add the right headers
                valueBody.addHeader(CONTENT_TYPE, "application/octet-stream");
                valueBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
                valueBody.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);
                valueBody.setContent(responseValue, "application/octet-stream");
                valueBody.addHeader(RestMessageHeaders.CONTENT_LENGTH, Integer.toString(responseValue.length));
                multiPartValues.addBodyPart(valueBody);
            } catch (MessagingException me) {
                logger.error("Exception while constructing value body part", me);
                keysOutputStream.close();
                throw me;
            }
        }
        try {
            // Add the inner multipart as the content of the outer body part
            keyBody.setContent(multiPartValues);
            multiPartKeys.addBodyPart(keyBody);
        } catch (MessagingException me) {
            logger.error("Exception while constructing key body part", me);
            keysOutputStream.close();
            throw me;
        }
    }
    message.setContent(multiPartKeys);
    message.saveChanges();
    try {
        multiPartKeys.writeTo(keysOutputStream);
    } catch (Exception e) {
        logger.error("Exception while writing mutipart to output stream", e);
        throw e;
    }
    ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
    responseContent.writeBytes(keysOutputStream.toByteArray());
    // Create the Response object
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    // Set the right headers
    response.setHeader(CONTENT_TYPE, "multipart/binary");
    response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
    // Copy the data into the payload
    response.setContent(responseContent);
    response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
    // Write the response to the Netty Channel
    if (logger.isDebugEnabled()) {
        String keyStr = getKeysHexString(this.versionedResponses.keySet());
        debugLog("GET_ALL", this.storeName, keyStr, startTimeInMs, System.currentTimeMillis(), numVectorClockEntries);
    }
    this.messageEvent.getChannel().write(response);
    if (performanceStats != null && isFromLocalZone) {
        recordStats(performanceStats, startTimeInMs, Tracked.GET_ALL);
    }
    keysOutputStream.close();
}
Also used : MessagingException(javax.mail.MessagingException) VectorClock(voldemort.versioning.VectorClock) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) Properties(java.util.Properties) MessagingException(javax.mail.MessagingException) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) ByteArray(voldemort.utils.ByteArray) List(java.util.List) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 70 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project SpringStepByStep by JavaProgrammerLB.

the class SendHTMLEmailWithTemplate method main.

public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    try {
        props.load(new FileInputStream(new File("settings.properties")));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    Session session = Session.getDefaultInstance(props, new Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("username", "******");
        }
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
        message.setSubject("Testing Subject");
        BodyPart body = new MimeBodyPart();
        // freemarker stuff.
        Configuration cfg = new Configuration();
        Template template = cfg.getTemplate("html-mail-template.ftl");
        Map<String, String> rootMap = new HashMap<String, String>();
        rootMap.put("to", "liubei");
        rootMap.put("body", "Sample html email using freemarker");
        rootMap.put("from", "liubei");
        Writer out = new StringWriter();
        template.process(rootMap, out);
        // freemarker stuff ends.
        /* you can add html tags in your text to decorate it. */
        body.setContent(out.toString(), "text/html");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(body);
        body = new MimeBodyPart();
        String filename = "hello.txt";
        DataSource source = new FileDataSource(filename);
        body.setDataHandler(new DataHandler(source));
        body.setFileName(filename);
        multipart.addBodyPart(body);
        message.setContent(multipart, "text/html;charset=utf-8");
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    System.out.println("Done....");
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) Template(freemarker.template.Template) StringWriter(java.io.StringWriter) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) StringWriter(java.io.StringWriter) Writer(java.io.Writer) Session(javax.mail.Session)

Aggregations

MimeBodyPart (javax.mail.internet.MimeBodyPart)172 MimeMultipart (javax.mail.internet.MimeMultipart)111 MimeMessage (javax.mail.internet.MimeMessage)65 MessagingException (javax.mail.MessagingException)64 IOException (java.io.IOException)49 DataHandler (javax.activation.DataHandler)39 ByteString (com.linkedin.data.ByteString)38 ByteArrayOutputStream (java.io.ByteArrayOutputStream)37 BodyPart (javax.mail.BodyPart)35 InternetAddress (javax.mail.internet.InternetAddress)31 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)30 Test (org.testng.annotations.Test)28 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)23 Multipart (javax.mail.Multipart)20 InputStream (java.io.InputStream)18 ArrayList (java.util.ArrayList)17 HashMap (java.util.HashMap)16 Session (javax.mail.Session)16 Date (java.util.Date)15 Properties (java.util.Properties)15