Example usage for javax.mail.internet MimeBodyPart MimeBodyPart

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

Introduction

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

Prototype

public MimeBodyPart() 

Source Link

Document

An empty MimeBodyPart object is created.

Usage

From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java

private void sendMail(DispatchContext sInfo, BIObject biobj, Map parMap, byte[] response, String retCT,
        String fileExt, IDataStore dataStore, String toBeAppendedToName, String toBeAppendedToDescription) {
    logger.debug("IN");
    try {/*w ww.java2  s. com*/

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        int smptPort = 25;

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";
        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        if ((user == null) || user.trim().equals("")) {
            logger.debug("Smtp user not configured");
            user = null;
        }
        //   throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals("")) {
            logger.debug("Smtp password not configured");
        }
        //   throw new Exception("Smtp password not configured");

        String mailSubj = sInfo.getMailSubj();
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parMap, null, false);

        String mailTxt = sInfo.getMailTxt();

        String[] recipients = findRecipients(sInfo, biobj, dataStore);
        if (recipients == null || recipients.length == 0) {
            logger.error("No recipients found for email sending!!!");
            return;
        }

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", smptPort);

        // open session
        Session session = null;

        // create autheticator object
        Authenticator auth = null;
        if (user != null) {
            auth = new SMTPAuthenticator(user, pass);
            props.put("mail.smtp.auth", "true");
            session = Session.getDefaultInstance(props, auth);
            logger.error("Session.getDefaultInstance(props, auth)");
        } else {
            session = Session.getDefaultInstance(props);
            logger.error("Session.getDefaultInstance(props)");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        String subject = mailSubj + " " + biobj.getName() + toBeAppendedToName;
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt + "\n" + toBeAppendedToDescription);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message

        SchedulerDataSource sds = new SchedulerDataSource(response, retCT,
                biobj.getName() + toBeAppendedToName + fileExt);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.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);
        // send message
        Transport.send(msg);
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
    } finally {
        logger.debug("OUT");
    }
}

From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java

public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) {
    String host = "smtp.gmail.com";
    message = "Some of the appliances in your house are running inefficient." + "\n"
            + "Kindly check or replace your appliance " + "\n"
            + "Check the attachment for details or visit your account";
    Properties props = System.getProperties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", 587);
    props.put("mail.smtp.user", from);

    Session session = Session.getDefaultInstance(props);
    MimeMessage mimeMessage = new MimeMessage(session);
    try {/*from   w  w w  .  j  a  va  2  s. c om*/
        mimeMessage.setFrom(new InternetAddress(from));
        mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        mimeMessage.setSubject("Alert from Energy Board");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(message);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(name_attach.getText() + ".png");
        multipart.addBodyPart(messageBodyPart);
        mimeMessage.setContent(multipart);

        SMTPTransport transport = (SMTPTransport) session.getTransport("smtps");
        transport.connect(host, from, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        System.out.println("sent");
        transport.close();
    } catch (MessagingException me) {

    }
}

From source file:nl.nn.adapterframework.http.HttpSender.java

protected void addMtomMultiPartToPostMethod(PostMethod hmethod, String message, ParameterValueList parameters,
        ParameterResolutionContext prc) throws SenderException, MessagingException, IOException {
    MyMimeMultipart mimeMultipart = new MyMimeMultipart("related");
    String start = null;//from w w  w .  jav a2  s .  c o m
    if (StringUtils.isNotEmpty(getInputMessageParam())) {
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(message, "application/xop+xml; charset=UTF-8; type=\"text/xml\"");
        start = "<" + getInputMessageParam() + ">";
        mimeBodyPart.setContentID(start);
        ;
        mimeMultipart.addBodyPart(mimeBodyPart);
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "appended (string)part [" + getInputMessageParam() + "] with value ["
                    + message + "]");
    }
    if (parameters != null) {
        for (int i = 0; i < parameters.size(); i++) {
            ParameterValue pv = parameters.getParameterValue(i);
            String paramType = pv.getDefinition().getType();
            String name = pv.getDefinition().getName();
            if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) {
                Object value = pv.getValue();
                if (value instanceof FileInputStream) {
                    FileInputStream fis = (FileInputStream) value;
                    String fileName = null;
                    String sessionKey = pv.getDefinition().getSessionKey();
                    if (sessionKey != null) {
                        fileName = (String) prc.getSession().get(sessionKey + "Name");
                    }
                    MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary");
                    mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT);
                    ByteArrayDataSource ds = new ByteArrayDataSource(fis, "application/octet-stream");
                    mimeBodyPart.setDataHandler(new DataHandler(ds));
                    mimeBodyPart.setFileName(fileName);
                    mimeBodyPart.setContentID("<" + name + ">");
                    mimeMultipart.addBodyPart(mimeBodyPart);
                    if (log.isDebugEnabled())
                        log.debug(getLogPrefix() + "appended (file)part [" + name + "] with value [" + value
                                + "] and name [" + fileName + "]");
                } else {
                    throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass()
                            + "] for parameter [" + name + "]");
                }
            } else {
                String value = pv.asStringValue("");
                MimeBodyPart mimeBodyPart = new MimeBodyPart();
                mimeBodyPart.setContent(value, "text/xml");
                if (start == null) {
                    start = "<" + name + ">";
                    mimeBodyPart.setContentID(start);
                } else {
                    mimeBodyPart.setContentID("<" + name + ">");
                }
                mimeMultipart.addBodyPart(mimeBodyPart);
                if (log.isDebugEnabled())
                    log.debug(
                            getLogPrefix() + "appended (string)part [" + name + "] with value [" + value + "]");
            }
        }
    }
    if (StringUtils.isNotEmpty(getMultipartXmlSessionKey())) {
        String multipartXml = (String) prc.getSession().get(getMultipartXmlSessionKey());
        if (StringUtils.isEmpty(multipartXml)) {
            log.warn(getLogPrefix() + "sessionKey [" + getMultipartXmlSessionKey() + "] is empty");
        } else {
            Element partsElement;
            try {
                partsElement = XmlUtils.buildElement(multipartXml);
            } catch (DomBuilderException e) {
                throw new SenderException(getLogPrefix() + "error building multipart xml", e);
            }
            Collection parts = XmlUtils.getChildTags(partsElement, "part");
            if (parts == null || parts.size() == 0) {
                log.warn(getLogPrefix() + "no part(s) in multipart xml [" + multipartXml + "]");
            } else {
                int c = 0;
                Iterator iter = parts.iterator();
                while (iter.hasNext()) {
                    c++;
                    Element partElement = (Element) iter.next();
                    //String partType = partElement.getAttribute("type");
                    String partName = partElement.getAttribute("name");
                    String partMimeType = partElement.getAttribute("mimeType");
                    String partSessionKey = partElement.getAttribute("sessionKey");
                    Object partObject = prc.getSession().get(partSessionKey);
                    if (partObject instanceof FileInputStream) {
                        FileInputStream fis = (FileInputStream) partObject;
                        MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary");
                        mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT);
                        ByteArrayDataSource ds = new ByteArrayDataSource(fis,
                                (partMimeType == null ? "application/octet-stream" : partMimeType));
                        mimeBodyPart.setDataHandler(new DataHandler(ds));
                        mimeBodyPart.setFileName(partName);
                        mimeBodyPart.setContentID("<" + partName + ">");
                        mimeMultipart.addBodyPart(mimeBodyPart);
                        if (log.isDebugEnabled())
                            log.debug(getLogPrefix() + "appended (file)part [" + partSessionKey
                                    + "]  with value [" + partObject + "] and name [" + partName + "]");
                    } else {
                        String partValue = (String) prc.getSession().get(partSessionKey);
                        MimeBodyPart mimeBodyPart = new MimeBodyPart();
                        mimeBodyPart.setContent(partValue, "text/xml");
                        if (start == null) {
                            start = "<" + partName + ">";
                            mimeBodyPart.setContentID(start);
                        } else {
                            mimeBodyPart.setContentID("<" + partName + ">");
                        }
                        mimeMultipart.addBodyPart(mimeBodyPart);
                        if (log.isDebugEnabled())
                            log.debug(getLogPrefix() + "appended (string)part [" + partSessionKey
                                    + "]  with value [" + partValue + "]");
                    }
                }
            }
        }
    }
    MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()));
    mimeMessage.setContent(mimeMultipart);
    mimeMessage.saveChanges();
    InputStreamRequestEntity request = new InputStreamRequestEntity(mimeMessage.getInputStream());
    hmethod.setRequestEntity(request);
    String contentTypeMtom = "multipart/related; type=\"application/xop+xml\"; start=\"" + start
            + "\"; start-info=\"text/xml\"; boundary=\"" + mimeMultipart.getBoundary() + "\"";
    Header header = new Header("Content-Type", contentTypeMtom);
    hmethod.addRequestHeader(header);
}

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 {/*from  ww w  .j a  v a  2s. c  om*/
        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.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) {/*from   w w w  .j  a v a  2s  .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:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java

/**
 * Sends an email to the given id including a link to the password page. The
 * link contains the refID./*from   ww  w . ja va  2s .  c o  m*/
 * 
 * @param emailType
 *            - refers to the email that shall be sent, 0 sends an email for
 *            newly registered users, 1 sends a standard password-reset
 *            email
 * @param emailaddress
 * @param refID
 * @return
 */
public boolean sendPasswordLinkToEmail(int emailType, User user, String refID) {

    String salutation = "";

    if (user.getGender().equalsIgnoreCase("male")) {
        salutation = "geehrter Herr " + user.getName();
    } else {
        salutation = "geehrte Frau " + user.getName();
    }

    MailAuthenticator auth = new MailAuthenticator(emailProperties.getProperty("mail.user"),
            emailProperties.getProperty("mail.user.password")); // Login

    Properties props = (Properties) emailProperties.clone();
    props.remove("mail.user");
    props.remove("mail.user.password");
    Session session = Session.getInstance(props, auth);

    String htmlContent = emailBody;
    htmlContent = htmlContent.replaceFirst("TITLE",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".title"));
    htmlContent = htmlContent.replaceFirst("MESSAGESUBJECT",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject"));
    htmlContent = htmlContent.replaceFirst("HEADER1",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".header1"));
    htmlContent = htmlContent.replaceFirst("MESSAGE",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".message"));
    htmlContent = htmlContent.replaceFirst("SALUTATION", salutation);
    htmlContent = htmlContent.replaceFirst("TOPLEVELDOMAIN",
            emailProperties.getProperty("mail.service.domain"));
    htmlContent = htmlContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name"));
    htmlContent = htmlContent.replaceFirst("REFERER", refID);
    htmlContent = htmlContent.replaceFirst("BCKRGIMAGE", "'cid:header-image'");
    htmlContent = htmlContent.replaceFirst("DASH", "'cid:dash'");

    String textContent = emailProperties.getProperty("mail.skeleton.type." + emailType + ".title") + " - "
            + emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject") + "\n \n"
            + emailProperties.getProperty("mail.skeleton.type." + emailType + ".message");

    textContent = textContent.replaceFirst("TOPLEVELDOMAIN",
            emailProperties.getProperty("mail.service.domain"));
    textContent = textContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name"));
    textContent = textContent.replaceFirst("REFERER", refID);
    textContent = textContent.replaceFirst("SALUTATION", salutation);
    textContent = textContent.replaceAll("<br>", "\n");

    try {

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(emailProperties.getProperty("mail.user")));
        msg.setRecipients(javax.mail.Message.RecipientType.TO, user.getEmailaddress());
        msg.setSentDate(new Date());
        msg.setSubject(emailProperties.getProperty("mail.skeleton.type." + emailType + ".subject"));

        Multipart mp = new MimeMultipart("alternative");

        // plaintext
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(textContent);
        mp.addBodyPart(textPart);

        // html
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlContent, "text/html; charset=UTF-8");
        mp.addBodyPart(htmlPart);

        MimeBodyPart imagePart = new MimeBodyPart();
        DataSource fds = null;
        try {
            fds = new FileDataSource(
                    new File(new URL((String) emailProperties.get("mail.image.headerbackground")).getFile()));
        } catch (MalformedURLException e) {
            Logger.getLogger(this.getClass()).error(e);
        }
        imagePart.setDataHandler(new DataHandler(fds));
        imagePart.setHeader("Content-ID", "header-image");
        mp.addBodyPart(imagePart);

        MimeBodyPart imagePart2 = new MimeBodyPart();
        DataSource fds2 = null;
        try {
            fds2 = new FileDataSource(
                    new File(new URL((String) emailProperties.get("mail.image.dash")).getFile()));
        } catch (MalformedURLException e) {
            Logger.getLogger(this.getClass()).error(e);
        }
        imagePart2.setDataHandler(new DataHandler(fds2));
        imagePart2.setHeader("Content-ID", "dash");
        mp.addBodyPart(imagePart2);

        msg.setContent(mp);

        Transport.send(msg);
    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
        return false;
    }

    return true;
}

From source file:org.liveSense.service.email.EmailServiceImpl.java

/**
 * {@inheritDoc}/* www. j  av a  2 s  .c  om*/
 */
@Override
public void sendEmailFromTemplateString(Session session, String template, Node resource, String subject,
        Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc,
        HashMap<String, Object> variables) throws Exception {
    boolean haveSession = false;

    try {
        if (session != null && session.isLive()) {
            haveSession = true;
        } else {
            session = repository.loginAdministrative(null);
        }

        if (template == null) {
            throw new RepositoryException("Template is null");
        }
        String html = templateNode(Md5Encrypter.encrypt(template), resource, template, variables);
        if (html == null)
            throw new RepositoryException("Template is empty");

        // create the messge.
        MimeMessage mimeMessage = new MimeMessage((javax.mail.Session) null);

        MimeMultipart rootMixedMultipart = new MimeMultipart("mixed");
        mimeMessage.setContent(rootMixedMultipart);

        MimeMultipart nestedRelatedMultipart = new MimeMultipart("related");
        MimeBodyPart relatedBodyPart = new MimeBodyPart();
        relatedBodyPart.setContent(nestedRelatedMultipart);
        rootMixedMultipart.addBodyPart(relatedBodyPart);

        MimeMultipart messageBody = new MimeMultipart("alternative");
        MimeBodyPart bodyPart = null;
        for (int i = 0; i < nestedRelatedMultipart.getCount(); i++) {
            BodyPart bp = nestedRelatedMultipart.getBodyPart(i);
            if (bp.getFileName() == null) {
                bodyPart = (MimeBodyPart) bp;
            }
        }
        if (bodyPart == null) {
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            nestedRelatedMultipart.addBodyPart(mimeBodyPart);
            bodyPart = mimeBodyPart;
        }
        bodyPart.setContent(messageBody, "text/alternative");

        // Create the plain text part of the message.
        MimeBodyPart plainTextPart = new MimeBodyPart();
        plainTextPart.setText(extractTextFromHtml(html), configurator.getEncoding());
        messageBody.addBodyPart(plainTextPart);

        // Create the HTML text part of the message.
        MimeBodyPart htmlTextPart = new MimeBodyPart();
        htmlTextPart.setContent(html, "text/html;charset=" + configurator.getEncoding()); // ;charset=UTF-8
        messageBody.addBodyPart(htmlTextPart);

        // Check if resource have nt:file childs adds as attachment
        if (resource != null && resource.hasNodes()) {
            NodeIterator iter = resource.getNodes();
            while (iter.hasNext()) {
                Node n = iter.nextNode();
                if (n.getPrimaryNodeType().isNodeType("nt:file")) {
                    // Part two is attachment
                    MimeBodyPart attachmentBodyPart = new MimeBodyPart();
                    InputStream fileData = n.getNode("jcr:content").getProperty("jcr:data").getBinary()
                            .getStream();
                    String mimeType = n.getNode("jcr:content").getProperty("jcr:mimeType").getString();
                    String fileName = n.getName();

                    DataSource source = new StreamDataSource(fileData, fileName, mimeType);
                    attachmentBodyPart.setDataHandler(new DataHandler(source));
                    attachmentBodyPart.setFileName(fileName);
                    attachmentBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
                    attachmentBodyPart.setContentID(fileName);
                    rootMixedMultipart.addBodyPart(attachmentBodyPart);
                }
            }
        }

        prepareMimeMessage(mimeMessage, resource, template, subject, replyTo, from, date, to, cc, bcc,
                variables);
        sendEmail(session, mimeMessage);

        //
    } finally {
        if (!haveSession && session != null) {
            if (session.hasPendingChanges()) {
                try {
                    session.save();
                } catch (Throwable th) {
                }
            }
            session.logout();
        }
    }
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * Sets the content for a message. Also attaches files to the message.
 * @throws MessagingException//from  w w  w.j  a v  a 2s . c o  m
 */
protected void setContent(String content, List<Attachment> attachments, MimeMessage msg, String contentType,
        String charset, String multipartSubtype) throws MessagingException {
    ArrayList<MimeBodyPart> embeddedAttachments = new ArrayList<MimeBodyPart>();
    if (attachments != null && attachments.size() > 0) {
        // Add attachments to messages
        for (Attachment attachment : attachments) {
            // attach the file to the message
            embeddedAttachments.add(createAttachmentPart(attachment));
        }
    }

    // if no direct attachments, keep the message simple and add the content as text.
    if (embeddedAttachments.size() == 0) {
        // if no contentType specified, go with text/plain
        if (contentType == null)
            msg.setText(content, charset);
        else
            msg.setContent(content, contentType);
    }
    // the multipart was constructed (ie. attachments available), use it as the message content
    else {
        // create a multipart container
        Multipart multipart = (multipartSubtype != null) ? new MimeMultipart(multipartSubtype)
                : new MimeMultipart();

        // create a body part for the message text
        MimeBodyPart msgBodyPart = new MimeBodyPart();
        if (contentType == null)
            msgBodyPart.setText(content, charset);
        else
            msgBodyPart.setContent(content, contentType);

        // add the message part to the container
        multipart.addBodyPart(msgBodyPart);

        // add attachments
        for (MimeBodyPart attachPart : embeddedAttachments) {
            multipart.addBodyPart(attachPart);
        }

        // set the multipart container as the content of the message
        msg.setContent(multipart);
    }
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * Attaches a file as a body part to the multipart message
 *
 * @param attachment// w  w  w.j  av  a  2 s  .c  om
 * @throws MessagingException
 */
private MimeBodyPart createAttachmentPart(Attachment attachment) throws MessagingException {
    DataSource source = attachment.getDataSource();
    MimeBodyPart attachPart = new MimeBodyPart();

    attachPart.setDataHandler(new DataHandler(source));
    attachPart.setFileName(attachment.getFilename());

    if (attachment.getContentTypeHeader() != null) {
        attachPart.setHeader("Content-Type", attachment.getContentTypeHeader());
    }

    if (attachment.getContentDispositionHeader() != null) {
        attachPart.setHeader("Content-Disposition", attachment.getContentDispositionHeader());
    }

    return attachPart;
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Decrypts the data of a message with all given certificates etc
 * @param info MessageInfo, the encryption algorith will be stored in the encryption type of this info
 * @param rawMessageData encrypted data, will be decrypted
 * @param contentType contentType of the data
 * @param privateKey receivers private key
 * @param certificate receivers certificate
 *///from www  .  ja  v a 2s  .c o m
public byte[] decryptData(AS2Message message, byte[] data, String contentType, PrivateKey privateKeyReceiver,
        X509Certificate certificateReceiver, String receiverCryptAlias) throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeBodyPart encryptedBody = new MimeBodyPart();
    encryptedBody.setHeader("content-type", contentType);
    encryptedBody.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    RecipientId recipientId = new JceKeyTransRecipientId(certificateReceiver);
    SMIMEEnveloped enveloped = new SMIMEEnveloped(encryptedBody);
    BCCryptoHelper helper = new BCCryptoHelper();
    String algorithm = helper.convertOIDToAlgorithmName(enveloped.getEncryptionAlgOID());
    if (algorithm.equals(BCCryptoHelper.ALGORITHM_3DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_3DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC2)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC2_UNKNOWN);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_128)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_128);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_192)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_192);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_256)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_256);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC4)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC4_UNKNOWN);
    } else {
        info.setEncryptionType(AS2Message.ENCRYPTION_UNKNOWN_ALGORITHM);
    }
    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    enveloped = null;
    encryptedBody = null;
    RecipientInformation recipient = recipients.get(recipientId);
    if (recipient == null) {
        //give some details about the required and used cert for the decryption
        Collection recipientList = recipients.getRecipients();
        Iterator iterator = recipientList.iterator();
        while (iterator.hasNext()) {
            RecipientInformation recipientInfo = (RecipientInformation) iterator.next();
            if (this.logger != null) {
                this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.inforequired",
                        new Object[] { info.getMessageId(), recipientInfo.getRID() }), info);
            }
        }
        if (this.logger != null) {
            this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.infoassigned",
                    new Object[] { info.getMessageId(), receiverCryptAlias, recipientId }), info);
        }
        throw new AS2Exception(AS2Exception.AUTHENTIFICATION_ERROR,
                "Error decrypting the message: Recipient certificate does not match.", message);
    }
    //Streamed decryption. Its also possible to use in memory decryption using getContent but that uses
    //far more memory.
    InputStream contentStream = recipient
            .getContentStream(new JceKeyTransEnvelopedRecipient(privateKeyReceiver).setProvider("BC"))
            .getContentStream();
    //InputStream contentStream = recipient.getContentStream(privateKeyReceiver, "BC").getContentStream();
    //threshold set to 20 MB: if the data is less then 20MB perform the operaion in memory else stream to disk
    DeferredFileOutputStream decryptedOutput = new DeferredFileOutputStream(20 * 1024 * 1024, "as2decryptdata_",
            ".mem", null);
    this.copyStreams(contentStream, decryptedOutput);
    decryptedOutput.flush();
    decryptedOutput.close();
    contentStream.close();
    byte[] decryptedData = null;
    //size of the data was < than the threshold
    if (decryptedOutput.isInMemory()) {
        decryptedData = decryptedOutput.getData();
    } else {
        //data has been written to a temp file: reread and return
        ByteArrayOutputStream memOut = new ByteArrayOutputStream();
        decryptedOutput.writeTo(memOut);
        memOut.flush();
        memOut.close();
        //finally delete the temp file
        boolean deleted = decryptedOutput.getFile().delete();
        decryptedData = memOut.toByteArray();
    }
    if (this.logger != null) {
        this.logger.log(Level.INFO,
                this.rb.getResourceString("decryption.done.alias",
                        new Object[] { info.getMessageId(), receiverCryptAlias,
                                this.rbMessage.getResourceString("encryption." + info.getEncryptionType()) }),
                info);
    }
    return (decryptedData);
}