Example usage for javax.mail.internet MimeMultipart MimeMultipart

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

Introduction

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

Prototype

public MimeMultipart() 

Source Link

Document

Default constructor.

Usage

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param runner//  w  w w  .j  a va 2 s  . c om
 * @param resultDir
 * @throws MessagingException
 * @throws IOException
 */
public void send(MultiHTMLSuiteRunner runner, File resultDir) throws MessagingException, IOException {

    MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setHeader("Content-Transfer-Encoding", "7bit");

    // To
    mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.getTo()));

    // From
    mimeMessage.setFrom(new InternetAddress(config.getFrom()));

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put("result", runner.getResult() ? "passed" : "failed");
    context.put("passedCount", new Integer(runner.getPassedCount()));
    context.put("failedCount", new Integer(runner.getFailedCount()));
    context.put("totalCount", new Integer(runner.getHtmlSuiteList().size()));
    context.put("startTime", new Date(runner.getStartTime()));
    context.put("endTime", new Date(runner.getEndTime()));
    context.put("htmlSuites", runner.getHtmlSuiteList());

    // subject
    mimeMessage.setSubject(TemplateUtils.merge(config.getSubject(), context), config.getCharset());

    // multipart message
    MimeMultipart content = new MimeMultipart();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(TemplateUtils.merge(config.getBody(), context), config.getCharset());
    content.addBodyPart(body);

    File resultArchive = createResultArchive(resultDir);

    MimeBodyPart attachmentFile = new MimeBodyPart();
    attachmentFile.setDataHandler(new DataHandler(new FileDataSource(resultArchive)));
    attachmentFile.setFileName(RESULT_ARCHIVE_FILE);
    content.addBodyPart(attachmentFile);

    mimeMessage.setContent(content);

    // send mail
    _send(mimeMessage);
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Send an email in html-format in iso-8859-1-encoding
 * /*from  ww  w .  j a  v  a  2s .  c om*/
 * @param subject the subject of the new mail
 * @param htmlMessage the content of the mail as html
 * @param alternativeTextMessage the content of the mail as text
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendHtmlMail(String subject, String htmlMessage, String alternativeTextMessage, String from,
        String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "iso-8859-1");
        msg.setSentDate(new Date());

        MimeMultipart multiPart = new MimeMultipart();
        BodyPart bodyPart = new MimeBodyPart();

        bodyPart.setText(alternativeTextMessage);
        multiPart.addBodyPart(bodyPart);

        bodyPart = new MimeBodyPart();
        bodyPart.setContent(htmlMessage, "text/html");
        multiPart.addBodyPart(bodyPart);

        multiPart.setSubType("alternative");

        msg.setContent(multiPart);
        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending html-mail: " + e.getLocalizedMessage());
    }
}

From source file:at.molindo.notify.channel.mail.AbstractMailClient.java

@Override
public synchronized void send(Dispatch dispatch) throws MailException {

    Message message = dispatch.getMessage();

    String recipient = dispatch.getParams().get(MailChannel.RECIPIENT);
    String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME);
    String subject = message.getSubject();

    try {//w ww . j av  a  2s .c om
        MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) {
            @Override
            protected void updateMessageID() throws MessagingException {
                String domain = _from.getAddress();
                int idx = _from.getAddress().indexOf('@');
                if (idx >= 0) {
                    domain = domain.substring(idx + 1);
                }
                setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">");
            }
        };
        mm.setFrom(_from);
        mm.setSender(_from);

        InternetAddress replyTo = getReplyTo();
        if (replyTo != null) {
            mm.setReplyTo(new Address[] { replyTo });
        }
        mm.setHeader("X-Mailer", "molindo-notify");
        mm.setSentDate(new Date());

        mm.setRecipient(RecipientType.TO,
                new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName()));
        mm.setSubject(subject, CharsetUtils.UTF_8.displayName());

        if (_format == Format.HTML) {
            if (message.getType() == Type.TEXT) {
                throw new MailException("can't send HTML mail from TEXT message", false);
            }
            mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");
        } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) {
            mm.setText(message.getText(), CharsetUtils.UTF_8.displayName());
        } else if (_format == Format.MULTI) {
            MimeBodyPart html = new MimeBodyPart();
            html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");

            MimeBodyPart text = new MimeBodyPart();
            text.setText(message.getText(), CharsetUtils.UTF_8.displayName());

            /*
             * The formats are ordered by how faithful they are to the
             * original, with the least faithful first and the most faithful
             * last. (http://en.wikipedia.org/wiki/MIME#Alternative)
             */
            MimeMultipart mmp = new MimeMultipart();
            mmp.setSubType("alternative");

            mmp.addBodyPart(text);
            mmp.addBodyPart(html);

            mm.setContent(mmp);
        } else {
            throw new NotifyRuntimeException(
                    "unexpected format (" + _format + ") or type (" + message.getType() + ")");
        }

        send(mm);

    } catch (final MessagingException e) {
        throw new MailException(
                "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e,
                isTemporary(e));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("utf8 unknown?", e);
    }
}

From source file:voldemort.coordinator.HttpGetAllRequestExecutor.java

public void writeResponse(Map<ByteArray, List<Versioned<byte[]>>> versionedResponses) throws Exception {
    // 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();//from w  ww. ja  va 2  s  . c om
        String contentLocationKey = "/" + this.storeName + "/" + new String(Base64.encodeBase64(key.get()));

        // Create the individual body part - for each key requested
        MimeBodyPart keyBody = new MimeBodyPart();
        try {
            // Add the right headers
            keyBody.addHeader(CONTENT_TYPE, "multipart/binary");
            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 serializedVC = CoordinatorUtils.getSerializedVectorClock(vectorClock);

            // 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(VoldemortHttpRequestHandler.X_VOLD_VECTOR_CLOCK, serializedVC);
                valueBody.setContent(responseValue, "application/octet-stream");

                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;
        }

    }
    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());

    // Update the stats
    if (this.coordinatorPerfStats != null) {
        long durationInNs = System.nanoTime() - startTimestampInNs;
        this.coordinatorPerfStats.recordTime(Tracked.GET_ALL, durationInNs);
    }

    // Write the response to the Netty Channel
    this.getRequestMessageEvent.getChannel().write(response);

    keysOutputStream.close();
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments)
        throws MessagingException {
    Transport t = null;//from w  w  w . j a va 2s . c o m

    try {
        MimeMessage message = new MimeMessage(session);

        t = session.getTransport("smtp");

        message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        if (attachments == null || attachments.size() < 1) {
            message.setText(text);
        } else {
            // create the message part 
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(text);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            try {
                for (InputStream attachment : attachments.keySet()) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");

                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR 
                    multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val
                }
            } catch (IOException e) {
                throw new MessagingException("cannot add an attachment to mail", e);
            }
            message.setContent(multipart);
        }

        t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

        t.sendMessage(message, message.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }

}

From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java

public boolean send() {
    String cc = null;// w  w w. j a v a 2  s.c  o m
    String bcc = null;
    String from = props.getProperty("mail.from.default");
    String to = props.getProperty("to");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + "with the subject '" + subject
            + "' and the body " + body);

    try {
        // Get a Session object
        Session session;

        if (authenticate) {
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        if (body != null) {
            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            multipart.addBodyPart(textBodyPart);
        }

        // need to create a multi-part message...
        // create the Multipart and add its parts to it

        // create and fill the first message part
        IPentahoStreamSource source = attachment;
        if (source == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }
        DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);

        // create the second message part
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();

        // attach the file to the message
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(attachmentName);

        multipart.addBodyPart(attachmentBodyPart);

        // add the Multipart to the message
        msg.setContent(multipart);

        msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$

    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:bo.com.offercruzmail.imp.FormadorMensajes.java

public static Multipart getMensajeUsuarioNoRegistrado() throws MessagingException {
    Multipart multiPartes = new MimeMultipart();
    multiPartes.addBodyPart(FormadorMensajes
            .getBodyPartEnvuelto(escapeHtml4("Lo siento no est registrado para poder usar este sistema")));
    return multiPartes;
}

From source file:org.talend.dataprep.api.service.mail.MailFeedbackSender.java

@Override
public void send(String subject, String body, String sender) {
    try {//from w ww. ja v a2  s  .c  o  m
        final String recipientList = StringUtils.join((new HashSet<>(Arrays.asList(recipients))).toArray(),
                ',');
        subject = subjectPrefix + subject;
        body = bodyPrefix + "<br/>" + body + "<br/>" + bodySuffix;

        InternetAddress from = new InternetAddress(this.sender);
        InternetAddress replyTo = new InternetAddress(sender);

        Properties p = new Properties();
        p.put("mail.smtp.host", smtpHost);
        p.put("mail.smtp.port", smtpPort);
        p.put("mail.smtp.starttls.enable", "true");
        p.put("mail.smtp.auth", "true");

        MailAuthenticator authenticator = new MailAuthenticator(userName, password);
        Session sendMailSession = Session.getInstance(p, authenticator);

        MimeMessage msg = new MimeMessage(sendMailSession);
        msg.setFrom(from);
        msg.setReplyTo(new Address[] { replyTo });
        msg.addRecipients(Message.RecipientType.TO, recipientList);

        msg.setSubject(subject, "UTF-8");
        msg.setSentDate(new Date());
        Multipart mainPart = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(body, "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        msg.setContent(mainPart);
        Transport.send(msg);

        LOGGER.debug("Sending mail:'{}' to '{}'", subject, recipients);
    } catch (Exception e) {
        throw new TDPException(APIErrorCodes.UNABLE_TO_SEND_MAIL, e);
    }
}

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

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

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

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);//from  ww w  . ja  va2 s  .  c  o  m
    Transport transport = mailSession.getTransport();

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

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

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

    List<String> fileNames = getAtchFileIds();

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

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

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

        mp.addBodyPart(mbp2);
    }

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

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

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

From source file:org.infoglue.common.util.mail.MailService.java

/**
 * @param attachments /*from   ww w  . j  ava 2  s .co  m*/
 *
 */
private Message createMessage(String from, String to, String bcc, String subject, String content,
        String contentType, String encoding, List attachments) throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);
        String contentTypeWithEncoding = contentType + ";charset=" + encoding;

        // message.setContent(content, contentType);
        message.setFrom(createInternetAddress(from));
        //message.setRecipient(Message.RecipientType.TO,
        //      createInternetAddress(to));
        message.setRecipients(Message.RecipientType.TO, createInternetAddresses(to));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc));
        // message.setSubject(subject);

        ((MimeMessage) message).setSubject(subject, encoding);
        MimeMultipart mp = new MimeMultipart();
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setDataHandler(new DataHandler(new StringDataSource(content, contentTypeWithEncoding, encoding)));
        mp.addBodyPart(mbp1);
        if (attachments != null) {
            for (Iterator it = attachments.iterator(); it.hasNext();) {
                File attachmentFile = (File) it.next();
                if (attachmentFile.exists()) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    attachment.setFileName(attachmentFile.getName());
                    attachment.setDataHandler(new DataHandler(new FileDataSource(attachmentFile)));
                    mp.addBodyPart(attachment);
                }
            }
        }
        message.setContent(mp);
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, contentTypeWithEncoding, encoding)));
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, "text/html")));

        return message;
    } catch (MessagingException e) {
        throw new SystemException("Unable to create the message.", e);
    }
}