Example usage for javax.mail.internet MimeBodyPart setDataHandler

List of usage examples for javax.mail.internet MimeBodyPart setDataHandler

Introduction

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

Prototype

@Override
public void setDataHandler(DataHandler dh) throws MessagingException 

Source Link

Document

This method provides the mechanism to set this body part's content.

Usage

From source file:com.threepillar.labs.meeting.email.EmailInviteImpl.java

@Override
public void sendInvite(final String subject, final String description, final Participant from,
        final List<Participant> attendees, final Date startDate, final Date endDate, final String location)
        throws Exception {

    this.properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port"));
    this.properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    this.properties.put("mail.smtp.socketFactory.fallback", "false");

    validate();/*from   www  .  j av  a 2  s .c om*/

    LOG.info("Sending meeting invite");
    LOG.debug("Mail Properties :: " + this.properties);

    Session session;
    if (password != null) {
        session = Session.getInstance(this.properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    } else {
        session = Session.getInstance(this.properties);
    }

    ICal cal = new ICal(subject, description, from, attendees, startDate, endDate, location);
    cal.init();

    StringBuffer sb = new StringBuffer();
    sb.append(from.getEmail());
    for (Participant bean : attendees) {
        if (sb.length() > 0) {
            sb.append(",");
        }
        sb.append(bean.getEmail());
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from.getEmail()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sb.toString()));
    message.setSubject(subject);
    Multipart multipart = new MimeMultipart();
    MimeBodyPart iCal = new MimeBodyPart();
    iCal.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(cal.toByteArray()),
            "text/calendar;method=REQUEST;charset=\"UTF-8\"")));

    LOG.debug("Calender Request :: \n" + cal.toString());

    multipart.addBodyPart(iCal);
    message.setContent(multipart);
    Transport.send(message);
}

From source file:it.cnr.icar.eric.common.RepositoryItemImpl.java

/**
 * Packages the RepositoryItem as a MimeMultiPart and returns it
 *
 * @deprecated sigElement/multipart attachment is not used anymore.
 *//*from ww  w  .  ja v a2  s .c  om*/
public MimeMultipart getMimeMultipart() throws RegistryException {
    MimeMultipart mp = null;
    try {
        //Create a multipart with two bodyparts
        //First bodypart is an XMLDSIG and second is the attached file
        mp = new MimeMultipart();

        //The signature part
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        trans.transform(new DOMSource(sigElement), new StreamResult(os));

        MimeBodyPart bp1 = new MimeBodyPart();
        bp1.addHeader("Content-ID", "payload1");
        bp1.setText(os.toString(), "utf-8");
        mp.addBodyPart(bp1);

        //The payload part
        MimeBodyPart bp2 = new MimeBodyPart();
        bp2.setDataHandler(handler);
        bp2.addHeader("Content-Type", handler.getContentType());
        bp2.addHeader("Content-ID", "payload2");
        mp.addBodyPart(bp2);
    } catch (MessagingException e) {
        throw new RegistryException(e);
    } catch (TransformerException e) {
        throw new RegistryException(e);
    }
    return mp;
}

From source file:com.adaptris.core.MimeEncoderImpl.java

protected MimeBodyPart payloadAsMimePart(AdaptrisMessage m) throws Exception {
    MimeBodyPart p = new MimeBodyPart();
    p.setDataHandler(new DataHandler(new MessageDataSource(m)));
    if (!isEmpty(getPayloadEncoding())) {
        p.setHeader(MimeConstants.HEADER_CONTENT_ENCODING, getPayloadEncoding());
    }// w  w  w. jav  a  2s .c o  m
    return p;
}

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {//from   w ww.ja v  a 2  s.c  o  m
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/*from   w w w.  jav a 2s .  c om*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, @SuppressWarnings("unused") final String port,
        @SuppressWarnings("unused") final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;
    Boolean fail = false;

    ArrayList<String> userAndPass = new ArrayList<String>();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host); //$NON-NLS-1$
    props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    boolean usingSSL = false;
    if (usingSSL) {
        props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
        props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    }

    Session session = Session.getInstance(props, null);

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
    }

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));
        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            InternetAddress[] address = { new InternetAddress(toEMailAddr) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

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

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        // set the Date: header
        msg.setSentDate(new Date());

        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                t.connect(host, userName, password);

                t.sendMessage(msg, msg.getAllRecipients());

                fail = false;
            } catch (MessagingException mex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
                instance.lastErrorMsg = mex.toString();

                Exception ex = null;
                if ((ex = mex.getNextException()) != null) {
                    ex.printStackTrace();
                    instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
                }

                //wrong username or password, get new one
                if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    fail = true;
                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) {//the user is done
                        return false;
                    }
                    // else
                    //try again
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }
            } finally {

                log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                t.close();
            }
        } while (fail && cnt < 6);

    } catch (MessagingException mex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        //mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return false;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);
        ex.printStackTrace();
    }

    if (fail) {
        return false;
    } //else
    return true;
}

From source file:org.nuxeo.ecm.automation.core.mail.Composer.java

public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType,
        List<Blob> attachments) throws TemplateException, IOException, MessagingException {
    if (textType == null) {
        textType = "plain";
    }/*ww w  .  j  a  v  a  2 s .c o  m*/
    Mailer.Message msg = mailer.newMessage();
    MimeMultipart mp = new MimeMultipart();
    MimeBodyPart body = new MimeBodyPart();
    String result = render(templateContent, ctx);
    body.setText(result, "UTF-8", textType);
    mp.addBodyPart(body);
    for (Blob blob : attachments) {
        MimeBodyPart a = new MimeBodyPart();
        a.setDataHandler(new DataHandler(new BlobDataSource(blob)));
        a.setFileName(blob.getFilename());
        mp.addBodyPart(a);
    }
    msg.setContent(mp);
    return msg;
}

From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message arg0) {
    ObjectMessage objectMessage = (ObjectMessage) arg0;
    try {//from w ww . j  a  va 2  s  .  c o  m
        Mail mail = (Mail) objectMessage.getObject();

        // Get properties
        String mailProtocol = getMailProtocol();
        String mailServer = getSmtpServer();
        String mailUser = getSmtpUser();
        String mailPort = getSmtpPort();
        String mailPassword = getSmtpPassword();

        // Initialize a mail session
        Properties props = new Properties();
        props.put("mail." + mailProtocol + ".host", mailServer);
        props.put("mail." + mailProtocol + ".port", mailPort);
        Session session = Session.getInstance(props);

        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mail.getSender()));
        for (String recipient : mail.getRecipients()) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(mail.getSubject(), "UTF-8");

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // Set the email message text and attachment
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(mail.getBody(), mail.getContentType());
        multipart.addBodyPart(messagePart);

        if (mail.getAttachmentData() != null) {
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(),
                    mail.getAttachmentContentType());
            DataHandler dataHandler = new DataHandler(byteArrayDataSource);
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(dataHandler);
            attachmentPart.setFileName(mail.getAttachmentFileName());

            multipart.addBodyPart(attachmentPart);
        }

        // Open transport and send message
        Transport transport = session.getTransport(mailProtocol);
        if (StringUtils.isNotBlank(mailUser)) {
            transport.connect(mailUser, mailPassword);
        } else {
            transport.connect();
        }
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (JMSException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e);
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e);
        throw new RuntimeException(e);
    }
}

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

/**
 * @param attachments /*  ww w  .  ja v a  2  s .  c  om*/
 *
 */
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);
    }
}

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

/**
 * @param runner//from   www .j  a va  2s. 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:com.meltmedia.cadmium.email.TestingMessageTransformer.java

public MimeBodyPart newOriginalBodyPart(MimeMessage message) throws MessagingException {
    // get the data handler for this message.
    DataHandler handler = message.getDataHandler();

    // add the original body to the new body part.
    MimeBodyPart originalPart = new MimeBodyPart();
    originalPart.setDataHandler(handler);
    originalPart.setHeader("Content-ID", "original-message");

    return originalPart;
}