Example usage for javax.mail.internet MimeMultipart addBodyPart

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

Introduction

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

Prototype

@Override
public synchronized void addBodyPart(BodyPart part) throws MessagingException 

Source Link

Document

Adds a Part to the multipart.

Usage

From source file:fsi_admin.JSmtpConn.java

@SuppressWarnings("rawtypes")
private boolean adjuntarArchivo(StringBuffer msj, BodyPart messagebodypart, MimeMultipart multipart,
        Vector archivos) {/*ww w.ja  v  a2  s  .c  om*/
    if (!archivos.isEmpty()) {
        FileItem actual = null;

        try {
            for (int i = 0; i < archivos.size(); i++) {
                InputStream inputStream = null;
                try {
                    actual = (FileItem) archivos.elementAt(i);
                    inputStream = actual.getInputStream();
                    byte[] sourceBytes = IOUtils.toByteArray(inputStream);
                    String name = actual.getName();

                    messagebodypart = new MimeBodyPart();

                    ByteArrayDataSource rawData = new ByteArrayDataSource(sourceBytes);
                    DataHandler data = new DataHandler(rawData);

                    messagebodypart.setDataHandler(data);
                    messagebodypart.setFileName(name);
                    multipart.addBodyPart(messagebodypart);
                    ////////////////////////////////////////////////
                    /*
                    messagebodypart = new MimeBodyPart();
                    DataSource source = new FileDataSource(new File(actual.getName()));
                                
                    byte[] sourceBytes = actual.get();
                    OutputStream sourceOS = source.getOutputStream();
                    sourceOS.write(sourceBytes);
                               
                    messagebodypart.setDataHandler(new DataHandler(source));
                    messagebodypart.setFileName(actual.getName());
                    multipart.addBodyPart(messagebodypart);
                    */
                    ///////////////////////////////////////////////////////

                } finally {
                    if (inputStream != null)
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }
            }
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            msj.append("Error de Mensajeria al cargar adjunto SMTP: " + e.getMessage());
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            msj.append("Error de Entrada/Salida al cargar adjunto SMTP: " + e.getMessage());
            return false;
        }

    } else
        return true;
}

From source file:au.aurin.org.controller.RestController.java

public Boolean sendEmail(final String randomUUIDString, final String password, final String email,
        final List<String> lstApps, final String fullName) throws IOException {
    final String clink = classmail.getUrl() + "authchangepassword/" + randomUUIDString;

    logger.info("Starting sending Email to:" + email);
    String msg = "";

    if (!fullName.equals("")) {
        msg = msg + "Dear " + fullName + "<br>";
    }//from   w ww  .j  a v a 2s .com
    Boolean lswWhatIf = false;
    if (lstApps != null) {
        //msg = msg + "You have been given access to the following applications: <br>";
        msg = msg + "<br>You have been given access to the following applications: <br>";
        for (final String st : lstApps) {
            if (st.toLowerCase().contains("whatif") || st.toLowerCase().contains("what if")) {

                lswWhatIf = true;
            }
            msg = "<br>" + msg + st + "<br>";
        }

    }

    msg = msg + "<br>Your current password is : " + password
            + " <br> To customise the password please change it using link below: <br> <a href='" + clink
            + "'> change password </a><br><br>After changing your password you can log in to the applications using your email and password. ";

    final String subject = "AURIN Workbench Access";

    final String from = classmail.getFrom();
    final String to = email;

    if (lswWhatIf == true) {
        msg = msg
                + "<br><br>If you require further support to establish a project within Online WhatIf please email your request to support@aurin.org.au";
        msg = msg + "<br>For other related requests please contact one of the members of the project team.";
        msg = msg + "<br><br>Kind Regards,";
        msg = msg + "<br>The Online WhatIf team<br>";
        msg = msg
                + "<br><strong>Prof Christopher Pettit</strong>&nbsp;&nbsp;&nbsp;&nbsp;Online WhatIf Project Director, City Futures (c.pettit@unsw.edu.au)";
        msg = msg
                + "<br><strong>Claudia Pelizaro</strong>&nbsp;&nbsp;&nbsp;&nbsp;Online WhatIf Project Manager, AURIN (claudia.pelizaro@unimelb.edu.au)";
        msg = msg
                + "<br><strong>Andrew Dingjan</strong>&nbsp;&nbsp;&nbsp;&nbsp;Director, AURIN (andrew.dingjan@unimelb.edu.au)";
        msg = msg
                + "<br><strong>Serryn Eagleson</strong>&nbsp;&nbsp;&nbsp;&nbsp;Manager Data and Business Analytics (serrynle@unimelb.edu.au)";

    } else {
        msg = msg + "<br><br>Kind Regards,";
        msg = msg + "<br>The AURIN Workbench team";
    }

    try {
        final Message message = new MimeMessage(getSession());

        message.addRecipient(RecipientType.TO, new InternetAddress(to));
        message.addFrom(new InternetAddress[] { new InternetAddress(from) });

        message.setSubject(subject);
        message.setContent(msg, "text/html");

        //////////////////////////////////
        final MimeMultipart multipart = new MimeMultipart("related");
        final BodyPart messageBodyPart = new MimeBodyPart();
        //final String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";

        msg = msg + "<br><br><img src=\"cid:AbcXyz123\" />";
        //msg = msg + "<img src=\"cid:image\">";
        messageBodyPart.setContent(msg, "text/html");
        // add it
        multipart.addBodyPart(messageBodyPart);

        /////// second part (the image)
        //      messageBodyPart = new MimeBodyPart();
        final URL peopleresource = getClass().getResource("/logo.jpg");
        logger.info(peopleresource.getPath());
        //            final DataSource fds = new FileDataSource(
        //                peopleresource.getPath());
        //
        //      messageBodyPart.setDataHandler(new DataHandler(fds));
        //      messageBodyPart.setHeader("Content-ID", "<image>");
        //      // add image to the multipart
        //      //multipart.addBodyPart(messageBodyPart);

        ///////////
        final MimeBodyPart imagePart = new MimeBodyPart();
        imagePart.attachFile(peopleresource.getPath());
        //      final String cid = "1";
        //      imagePart.setContentID("<" + cid + ">");
        imagePart.setHeader("Content-ID", "AbcXyz123");
        imagePart.setDisposition(MimeBodyPart.INLINE);
        multipart.addBodyPart(imagePart);

        // put everything together
        message.setContent(multipart);
        ////////////////////////////////

        Transport.send(message);
        logger.info("Email sent to:" + email);
    } catch (final Exception mex) {
        logger.info(mex.toString());
        return false;
    }

    return true;
}

From source file:com.warsaw.data.controller.LoginController.java

private Message buildEmail(Session session, String to) throws Exception {
    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(EMAIL));

    // Set To: header field of the header.
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

    // Set Subject: header field
    message.setSubject("Testing Subject");

    // This mail has 2 part, the BODY and the embedded image
    MimeMultipart multipart = new MimeMultipart("related");

    // first part (the html)
    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<img style='width:800px' src=\"cid:image1\"><br/>" + "Dzie dobry,<br/><br/>"
            + "witamy na portalu TrasyPoWarszawsku.pl, na ktrym zostalo "
            + "zaoone konto<br/> dla osoby o danych: Jan Marian Ptak. W celu zakoczenia procesu tworzenia "
            + "konta prosimy uy linku aktywacyjnego:<br/><br/>"
            + "<a href='https://test.puesc.gov.pl?link=Gkhh&%JK.'>https://test.puesc.gov.pl?link=Gkhh&%JK.</a><br/><br/>"
            + "Na wywietlonym ekranie prosz wprowadzi zdefiniowane przez siebie haso awaryjne. Po prawidowym"
            + " wprowadzeniu danych<br/> oraz  ustawieniu nowego  hasa dostpowego  konto  na portalu PUESC zostanie aktywowane.<br/>"
            + "Link aktywacyjny pozostanie wany przez 24 godziny od momentu  otrzymania niniejszej wiadomoci.<br/><br/>"
            + "<img style='width:800px' src=\"cid:image2\"><br/><br/>" + "Z powaaniem<br/><br/>"
            + "Zesp portalu PUESC<br/>" + "puesc@mofnet.gov.pl<br/>"
            + "<a href='http://puesc.gov.pl'>http://puesc.gov.pl</a>";

    messageBodyPart.setContent(htmlText, "text/html; charset=ISO-8859-2");
    // add it/*  ww  w  . j a  va  2s  . c  o m*/
    multipart.addBodyPart(messageBodyPart);

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource("C:\\Users\\Pawel\\Desktop\\header.png");

    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image1>");

    // add image to the multipart
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    //  URL url = new URL("http://ns3342351.ovh.net:8080/seap_lf_graphicsLayout_theme/images/refresh.png");
    // URLDataSource fds1 =new URLDataSource(url);
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image2>");
    multipart.addBodyPart(messageBodyPart);

    // put everything together
    message.setContent(multipart);

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    try {
        message.writeTo(b);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return message;
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

private void addFormMultipart(HttpRequestInterface<?> request, MimeMultipart formMp, String name, String value)
        throws MessagingException {
    MimeBodyPart part = new MimeBodyPart();

    if (value.startsWith("file:")) {
        String fileName = value.substring(5);
        File file = new File(fileName);
        part.setDisposition("form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"");
        if (file.exists()) {
            part.setDataHandler(new DataHandler(new FileDataSource(file)));
        } else {//from   ww  w  .  j a v a 2 s  .c om
            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getName().equals(fileName)) {
                    part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));
                    break;
                }
            }
        }

        part.setHeader("Content-Type", ContentTypeHandler.getContentTypeFromFilename(file.getName()));
        part.setHeader("Content-Transfer-Encoding", "binary");
    } else {
        part.setDisposition("form-data; name=\"" + name + "\"");
        part.setText(value, System.getProperty("soapui.request.encoding", request.getEncoding()));
    }

    if (part != null) {
        formMp.addBodyPart(part);
    }
}

From source file:com.aurel.track.util.emailHandling.MailBuilder.java

private void includeImageLogo(MimeMultipart mimeMultipart) {
    BodyPart messageBodyPart;// w  w w.j ava 2s  . c o m
    ArrayList<String> imageFiles = new ArrayList<String>();
    imageFiles.add("tracklogo.gif");
    // more images can be added here
    ArrayList<String> cids = new ArrayList<String>();
    cids.add("logo");
    // for each image there should be a cid here

    URL imageURL = null;
    for (int i = 0; i < imageFiles.size(); ++i) {
        try {
            DataSource ds = null;
            messageBodyPart = new MimeBodyPart();
            InputStream in = null;
            in = ImageAction.class.getClassLoader().getResourceAsStream(imageFiles.get(i));
            int length = imageFiles.get(i).length();
            String type = imageFiles.get(i).substring(length - 4, length - 1);
            if (in != null) {
                ds = new ByteArrayDataSource(in, "image/" + type);
                System.err.println(type);
            } else {
                String theResource = "/WEB-INF/classes/resources/MailTemplates/" + imageFiles.get(i);
                imageURL = servletContext.getResource(theResource);
                ds = new URLDataSource(imageURL);
            }
            messageBodyPart.setDataHandler(new DataHandler(ds));
            messageBodyPart.setHeader("Content-ID", cids.get(i));
            messageBodyPart.setDisposition("inline");
            // add it
            mimeMultipart.addBodyPart(messageBodyPart);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            // what shall we do here?
        }
    }
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!/*from   w  w  w .j av a 2  s.c o m*/
 *
 * @param multipart DOCUMENT ME!
 * @param file DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, File file, String charset) throws MessagingException {
    // UNDONE how to specify the character set of the file???
    MimeBodyPart xbody = new MimeBodyPart();
    FileDataSource xds = new FileDataSource(file);
    DataHandler xdh = new DataHandler(xds);
    xbody.setDataHandler(xdh);

    //System.out.println(xdh.getContentType());
    // UNDONE
    // xbody.setContentLanguage( String ); // this could be language from Locale
    // xbody.setContentMD5( String md5 ); // don't know about this yet
    xbody.setDescription("File Attachment: " + file.getName(), charset);
    xbody.setDisposition(Part.ATTACHMENT);
    MessageUtilities.setFileName(xbody, file.getName(), charset);

    multipart.addBodyPart(xbody);
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

public void sendEmail(javax.mail.Session session, boolean rich, InternetAddress from,
        Collection<InternetAddress> to, Collection<InternetAddress> cc, Collection<InternetAddress> bcc,
        String subject, String body, Collection<MimeBodyPart> parts) throws MessagingException {
    MimeMultipart mp = new MimeMultipart("mixed");
    body = StringUtils.defaultString(body);

    // Adds text parts from passed body
    if (rich) {//  ww  w. ja  v  a  2 s  .  co m
        MimeMultipart alternative = new MimeMultipart("alternative");
        MimeBodyPart mbp2 = new MimeBodyPart();
        mbp2.setContent(body, MailUtils.buildPartContentType("text/html", "UTF-8"));
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(MailUtils.htmlToText(MailUtils.htmlunescapesource(body)),
                MailUtils.buildPartContentType("text/plain", "UTF-8"));
        alternative.addBodyPart(mbp1);
        alternative.addBodyPart(mbp2);
        MimeBodyPart altbody = new MimeBodyPart();
        altbody.setContent(alternative);
        mp.addBodyPart(altbody);
    } else {
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(body, MailUtils.buildPartContentType("text/plain", "UTF-8"));
        mp.addBodyPart(mbp1);
    }

    // Adds remaining parts to the mixed one
    if (parts != null) {
        for (MimeBodyPart p : parts) {
            mp.addBodyPart(p);
        }
    }

    sendEmail(session, from, to, cc, bcc, subject, mp);
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

public void sendEmail(javax.mail.Session session, boolean rich, InternetAddress from, InternetAddress[] to,
        InternetAddress[] cc, InternetAddress[] bcc, String subject, String body, MimeBodyPart[] parts)
        throws MessagingException {

    //Session session=getGlobalMailSession(pid.getDomainId());
    MimeMessage msg = new MimeMessage(session);
    try {// ww w  . j a  v a  2 s  . c o  m
        subject = MimeUtility.encodeText(subject);
    } catch (Exception exc) {
    }
    msg.setSubject(subject);
    msg.addFrom(new InternetAddress[] { from });

    if (to != null)
        for (InternetAddress addr : to) {
            msg.addRecipient(Message.RecipientType.TO, addr);
        }

    if (cc != null)
        for (InternetAddress addr : cc) {
            msg.addRecipient(Message.RecipientType.CC, addr);
        }

    if (bcc != null)
        for (InternetAddress addr : bcc) {
            msg.addRecipient(Message.RecipientType.BCC, addr);
        }

    body = StringUtils.defaultString(body);
    MimeMultipart mp = new MimeMultipart("mixed");
    if (rich) {
        MimeMultipart alternative = new MimeMultipart("alternative");
        MimeBodyPart mbp2 = new MimeBodyPart();
        mbp2.setContent(body, MailUtils.buildPartContentType("text/html", "UTF-8"));
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(MailUtils.htmlToText(MailUtils.htmlunescapesource(body)),
                MailUtils.buildPartContentType("text/plain", "UTF-8"));
        alternative.addBodyPart(mbp1);
        alternative.addBodyPart(mbp2);
        MimeBodyPart altbody = new MimeBodyPart();
        altbody.setContent(alternative);
        mp.addBodyPart(altbody);
    } else {
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(body, MailUtils.buildPartContentType("text/plain", "UTF-8"));
        mp.addBodyPart(mbp1);
    }

    if (parts != null) {
        for (MimeBodyPart part : parts)
            mp.addBodyPart(part);
    }

    msg.setContent(mp);

    msg.setSentDate(new java.util.Date());

    Transport.send(msg);
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!/*from  www. j  a  v a  2 s.co  m*/
 *
 * @param multipart DOCUMENT ME!
 * @param text DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param disposition DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, String text, String charset, String disposition,
        boolean isHtml) throws MessagingException {
    int xid = multipart.getCount() + 1;

    MimeBodyPart xbody = new MimeBodyPart();

    String xname = null;

    if (isHtml) {
        xname = "HTML" + xid + ".html";
        xbody.setContent(text, "text/html" + "; charset=" + charset);
        xbody.setDescription("Html Attachment: " + xname, charset);
    } else {
        xname = "TEXT" + xid + ".txt";
        xbody.setText(text, charset);
        xbody.setDescription("Text Attachment: " + xname, charset);
    }

    // UNDONE
    //xbody.setContentLanguage( String ); // this could be language from Locale
    //xbody.setContentMD5( String md5 ); // don't know about this yet        
    xbody.setDisposition(disposition);
    MessageUtilities.setFileName(xbody, xname, charset);

    multipart.addBodyPart(xbody);
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!// w  w w.  j ava 2 s  . c o  m
 *
 * @param multipart DOCUMENT ME!
 * @param part DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, Part part, String charset) throws MessagingException {
    MimeBodyPart xbody = new MimeBodyPart();
    PartDataSource xds = new PartDataSource(part);
    DataHandler xdh = new DataHandler(xds);
    xbody.setDataHandler(xdh);

    int xid = multipart.getCount() + 1;
    String xtext;

    // UNDONE
    //xbody.setContentLanguage( String ); // this could be language from Locale
    //xbody.setContentMD5( String md5 ); // don't know about this yet
    xtext = part.getDescription();

    if (xtext == null) {
        xtext = "Part Attachment: " + xid;
    }

    xbody.setDescription(xtext, charset);

    xtext = getContentDisposition(part).getType();
    xbody.setDisposition(xtext);

    xtext = MessageUtilities.getFileName(part);

    if ((xtext == null) || (xtext.length() < 1)) {
        xtext = "PART" + xid;
    }

    MessageUtilities.setFileName(xbody, xtext, charset);

    multipart.addBodyPart(xbody);
}