Example usage for javax.activation FileDataSource FileDataSource

List of usage examples for javax.activation FileDataSource FileDataSource

Introduction

In this page you can find the example usage for javax.activation FileDataSource FileDataSource.

Prototype

public FileDataSource(String name) 

Source Link

Document

Creates a FileDataSource from the specified path name.

Usage

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 w w w .j a  v  a2s  .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.wso2.carbon.webapp.mgt.WebappAdmin.java

/**
 * Downloads the webapp archive (.war) file
 *
 * @param fileName   name of the .war that needs to be downloaded
 * @param webappType application type//from w  w  w .  ja  v a2s  .  c  o  m
 * @param hostName   virtualhost
 * @return the corresponding data handler of the .war that needs to be downloaded
 */
public DataHandler downloadWarFileHandler(String fileName, String hostName, String webappType) {
    String repoPath = getAxisConfig().getRepository().getPath();
    String appsPath = getWebappDeploymentFile(fileName, hostName, webappType);

    File webAppFile = new File(appsPath);
    DataHandler handler = null;

    if (webAppFile.isDirectory()) {
        String zipTo = "tmp" + File.separator + fileName + ".zip";
        File fDownload = new File(zipTo);
        ArchiveManipulator archiveManipulator = new ArchiveManipulator();
        synchronized (this) {
            try {
                archiveManipulator.archiveDir(zipTo, webAppFile.getAbsolutePath());
                FileDataSource datasource = new FileDataSource(fDownload);
                handler = new DataHandler(datasource);
            } catch (IOException e) {
                log.error("Error downloading WAR file.", e);
            }
        }
    } else {
        FileDataSource datasource = new FileDataSource(new File(appsPath));
        handler = new DataHandler(datasource);
    }
    return handler;
}

From source file:org.enlacerh.util.FileUploadController.java

/**
 * Mtodo que enva los recibos de pago a cada usuario
 * @throws IOException /*from  w ww .  java 2  s.c om*/
 * @throws NumberFormatException 
 * **/
public void enviarRP(String to, String laruta, String file) throws NumberFormatException, IOException {
    try {
        //System.out.println("Enviando recibo");
        //System.out.println(jndimail());
        Context initContext = new InitialContext();
        Session session = (Session) initContext.lookup(jndimail());
        // Crear el mensaje a enviar
        MimeMessage mm = new MimeMessage(session);

        // Establecer las direcciones a las que ser enviado
        // el mensaje (test2@gmail.com y test3@gmail.com en copia
        // oculta)
        // mm.setFrom(new
        // InternetAddress("opennomina@dvconsultores.com"));
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Establecer el contenido del mensaje
        mm.setSubject(getMessage("mailRP"));
        //mm.setText(getMessage("mailContent"));

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setContent(getMessage("mailRPcontent"), "text/html; charset=utf-8");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = laruta + File.separator + file + ".pdf";
        javax.activation.DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(file + ".pdf");
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        mm.setContent(multipart);

        // Enviar el correo electrnico
        Transport.send(mm);
        //System.out.println("Correo enviado exitosamente a :" + to);
        //System.out.println("Fin recibo");
    } catch (Exception e) {
        msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage() + ": " + to, "");
        FacesContext.getCurrentInstance().addMessage(null, msj);
        e.printStackTrace();
    }
}

From source file:com.photon.phresco.util.Utility.java

public static void sendTemplateEmail(String[] toAddr, String fromAddr, String user, String subject, String body,
        String username, String password, String host, String screen, String build) throws PhrescoException {

    List<String> lists = Arrays.asList(toAddr);
    if (fromAddr == null) {
        fromAddr = "phresco.do.not.reply@gmail.com";
        username = "phresco.do.not.reply@gmail.com";
        password = "phresco123";
    }/*from w  w w.  j  a  v a 2  s.  com*/
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    Session session = Session.getDefaultInstance(props, new LoginAuthenticator(username, password));
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddr));
        List<Address> emailsList = getEmailsList(lists);
        Address[] dsf = new Address[emailsList.size()];
        message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf));
        message.setSubject(subject);
        DataSource source = new FileDataSource(body);
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("Error.txt");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();
        DataSource source2 = new FileDataSource(screen);
        messageBodyPart2.setDataHandler(new DataHandler(source2));
        messageBodyPart2.setFileName("Error.jpg");
        multipart.addBodyPart(messageBodyPart2);
        MimeBodyPart mainPart = new MimeBodyPart();
        String content = "<b>Phresco framework error report<br><br>User Name:&nbsp;&nbsp;" + user
                + "<br> Email Address:&nbsp;&nbsp;" + fromAddr + "<br>Build No:&nbsp;&nbsp;" + build;
        mainPart.setContent(content, "text/html");
        multipart.addBodyPart(mainPart);
        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new PhrescoException(e);
    }
}

From source file:it.cnr.icar.eric.client.ui.swing.RegistryBrowser.java

/**
 * Import RegistryObjects defined in an XML file within a ebRS
 * SubmitObjectsRequest and publish them to the registry user current user
 * context./*from   w  ww .j ava  2s.  co  m*/
 */
private void importFromFile() {
    if (isAuthenticated()) {
        try {
            int returnVal = fileChooser.showOpenDialog(this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File requestFile = fileChooser.getSelectedFile();
                File parentDirectory = requestFile.getParentFile();
                Unmarshaller unmarshaller = BindingUtility.getInstance().getJAXBContext().createUnmarshaller();

                SubmitObjectsRequest submitRequest = (SubmitObjectsRequest) unmarshaller.unmarshal(requestFile);
                HashMap<String, Object> attachMap = new HashMap<String, Object>(); // id
                // to
                // attachments
                // map

                // Look for special temporary Slot on ExtrinsicObjects to
                // resolve to RepositoryItem
                // If a file in same directory is found with filename same
                // as slot value
                // then assume it is the matching RepositoryItem

                // List ros =
                // submitRequest.getRegistryObjectList().getIdentifiable();
                //List<IdentifiableType> ebIdentifiableTypeList = (List<IdentifiableType>) BindingUtility
                //      .getInstance().getIdentifiableTypeList(submitRequest.getRegistryObjectList());

                // Iterator iter=ros.iterator();
                //Iterator<IdentifiableType> iter = ebIdentifiableTypeList.iterator();

                List<?> ros = submitRequest.getRegistryObjectList().getIdentifiable();
                Iterator<?> iter = ros.iterator();

                while (iter.hasNext()) {
                    Object obj = iter.next();
                    if (obj instanceof ExtrinsicObjectType) {
                        ExtrinsicObjectType eo = (ExtrinsicObjectType) obj;
                        @SuppressWarnings("rawtypes")
                        HashMap slotsMap = BindingUtility.getInstance().getSlotsFromRegistryObject(eo);
                        @SuppressWarnings("static-access")
                        String slotName = BindingUtility
                                .getInstance().CANONICAL_SLOT_EXTRINSIC_OBJECT_REPOSITORYITEM_URL;
                        String riURLStr = null;
                        if (slotsMap.containsKey(slotName)) {
                            riURLStr = (String) slotsMap.get(slotName);

                            // Remove transient slot
                            slotsMap.remove(slotName);
                            eo.getSlot().clear();
                            BindingUtility.getInstance().addSlotsToRegistryObject(eo, slotsMap);
                        } else if (slotsMap.containsKey(BindingUtility.CANONICAL_SLOT_CONTENT_LOCATOR)) {
                            riURLStr = (String) slotsMap.get(BindingUtility.CANONICAL_SLOT_CONTENT_LOCATOR);
                            if (isExternalURL(riURLStr)) {
                                // Dont import a repository item if URL is
                                // external
                                riURLStr = null;
                            }
                        }

                        if (riURLStr != null) {
                            File riFile = new File(parentDirectory, riURLStr);
                            DataHandler riDataHandler = new DataHandler(new FileDataSource(riFile));
                            attachMap.put(eo.getId(), riDataHandler);
                        }
                    }
                }
                LifeCycleManagerImpl lcm = (LifeCycleManagerImpl) (client.getBusinessLifeCycleManager());
                ClientRequestContext context = new ClientRequestContext("RegistryBrowser:importFromFile",
                        submitRequest);
                context.setRepositoryItemsMap(attachMap);
                BulkResponse br = lcm.doSubmitObjectsRequest(context);
                JAXRUtility.checkBulkResponse(br);
                displayInfo(resourceBundle.getString("message.info.ImportSuccessful"));
            }
        } catch (JAXBException e) {
            RegistryBrowser.displayError(resourceBundle.getString("message.error.InvalidEbRRSyntax"), e);
        } catch (Exception e) {
            RegistryBrowser.displayError(e);
        }
    } else {
        RegistryBrowser.displayError(resourceBundle.getString("message.error.mustBeLoggedIn"));
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave)
        throws Exception {
    MimeMessage msg = null;/*ww w  .  j  a  v a  2s.  co m*/
    boolean success = true;

    String[] to = SimpleMessage.breakAddr(smsg.getTo());
    String[] cc = SimpleMessage.breakAddr(smsg.getCc());
    String[] bcc = SimpleMessage.breakAddr(smsg.getBcc());
    String replyTo = smsg.getReplyTo();

    msg = new MimeMessage(mainAccount.getMailSession());
    msg.setFrom(getInternetAddress(from));
    InternetAddress ia = null;

    //set the TO recipient
    for (int q = 0; q < to.length; q++) {
        //        Service.logger.debug("to["+q+"]="+to[q]);
        to[q] = to[q].replace(',', ' ');
        try {
            ia = getInternetAddress(to[q]);
        } catch (AddressException exc) {
            throw new AddressException(to[q]);
        }
        msg.addRecipient(Message.RecipientType.TO, ia);
    }

    //set the CC recipient
    for (int q = 0; q < cc.length; q++) {
        cc[q] = cc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(cc[q]);
        } catch (AddressException exc) {
            throw new AddressException(cc[q]);
        }
        msg.addRecipient(Message.RecipientType.CC, ia);
    }

    //set BCC recipients
    for (int q = 0; q < bcc.length; q++) {
        bcc[q] = bcc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(bcc[q]);
        } catch (AddressException exc) {
            throw new AddressException(bcc[q]);
        }
        msg.addRecipient(Message.RecipientType.BCC, ia);
    }

    //set reply to addr
    if (replyTo != null && replyTo.length() > 0) {
        Address[] replyaddr = new Address[1];
        replyaddr[0] = getInternetAddress(replyTo);
        msg.setReplyTo(replyaddr);
    }

    //add any header
    String headerLines[] = smsg.getHeaderLines();
    for (int i = 0; i < headerLines.length; ++i) {
        if (!headerLines[i].startsWith("Sonicle-reply-folder")) {
            msg.addHeaderLine(headerLines[i]);
        }
    }

    //add reply/references
    String inreplyto = smsg.getInReplyTo();
    String references[] = smsg.getReferences();
    String replyfolder = smsg.getReplyFolder();
    if (inreplyto != null) {
        msg.setHeader("In-Reply-To", inreplyto);
    }
    if (references != null && references[0] != null) {
        msg.setHeader("References", references[0]);
    }
    if (tosave) {
        if (replyfolder != null) {
            msg.setHeader("Sonicle-reply-folder", replyfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }

    //add forward data
    String forwardedfrom = smsg.getForwardedFrom();
    String forwardedfolder = smsg.getForwardedFolder();
    if (forwardedfrom != null) {
        msg.setHeader("Forwarded-From", forwardedfrom);
    }
    if (tosave) {
        if (forwardedfolder != null) {
            msg.setHeader("Sonicle-forwarded-folder", forwardedfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }
    //set the subject
    String subject = smsg.getSubject();
    try {
        //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null);
        subject = MimeUtility.encodeText(smsg.getSubject());
    } catch (Exception exc) {
    }
    msg.setSubject(subject);

    //set priority
    int priority = smsg.getPriority();
    if (priority != 3) {
        msg.setHeader("X-Priority", "" + priority);

        //set receipt
    }
    String receiptTo = from;
    try {
        receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null);
    } catch (Exception exc) {
    }
    if (smsg.getReceipt()) {
        msg.setHeader("Disposition-Notification-To", from);

        //see if there are any new attachments for the message
    }
    int noAttach;
    int newAttach;

    if (attachments == null) {
        newAttach = 0;
    } else {
        newAttach = attachments.size();
    }

    //get the array of the old attachments
    Part[] oldParts = smsg.getAttachments();

    //check if there are old attachments
    if (oldParts == null) {
        noAttach = 0;
    } else { //old attachments exist
        noAttach = oldParts.length;
    }

    if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) {
        // create the main Multipart
        MimeMultipart mp = new MimeMultipart("mixed");
        MimeMultipart unrelated = null;

        String textcontent = smsg.getTextContent();
        //if is text, or no alternative text is available, add the content as one single body part
        //else create a multipart/alternative with both rich and text mime content
        if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) {
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            mp.addBodyPart(mbp1);
        } else {
            MimeMultipart alternative = new MimeMultipart("alternative");
            //the rich part
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            //the text part
            MimeBodyPart mbp1 = new MimeBodyPart();

            /*          ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length());
             com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos);
             for(int i=0;i<textcontent.length();++i) {
             try {
             qpe.write(textcontent.charAt(i));
             } catch(IOException exc) {
             Service.logger.error("Exception",exc);
             }
             }
             textcontent=new String(bos.toByteArray());*/
            mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8"));
            //          mbp1.setHeader("Content-transfer-encoding","quoted-printable");

            alternative.addBodyPart(mbp1);
            alternative.addBodyPart(mbp2);

            MimeBodyPart altbody = new MimeBodyPart();
            altbody.setContent(alternative);

            mp.addBodyPart(altbody);
        }

        if (noAttach > 0) { //if there are old attachments
            // create the parts with the attachments
            //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach];
            //Part[] mbps2 = new Part[noAttach];

            //for(int e = 0;e < noAttach;e++) {
            //  mbps2[e] = (Part)oldParts[e];
            //}//end for e
            //add the old attachment parts
            for (int r = 0; r < noAttach; r++) {
                Object content = null;
                String contentType = null;
                String contentFileName = null;
                if (oldParts[r] instanceof Message) {
                    //                Service.logger.debug("Attachment is a message");
                    Message msgpart = (Message) oldParts[r];
                    MimeMessage mm = new MimeMessage(mainAccount.getMailSession());
                    mm.addFrom(msgpart.getFrom());
                    mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO));
                    mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC));
                    mm.setRecipients(Message.RecipientType.BCC,
                            msgpart.getRecipients(Message.RecipientType.BCC));
                    mm.setReplyTo(msgpart.getReplyTo());
                    mm.setSentDate(msgpart.getSentDate());
                    mm.setSubject(msgpart.getSubject());
                    mm.setContent(msgpart.getContent(), msgpart.getContentType());
                    content = mm;
                    contentType = "message/rfc822";
                } else {
                    //                Service.logger.debug("Attachment is not a message");
                    content = oldParts[r].getContent();
                    if (!(content instanceof MimeMultipart)) {
                        contentType = oldParts[r].getContentType();
                        contentFileName = oldParts[r].getFileName();
                    }
                }
                MimeBodyPart mbp = new MimeBodyPart();
                if (contentFileName != null) {
                    mbp.setFileName(contentFileName);
                    //              Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName);
                    contentType += "; name=\"" + contentFileName + "\"";
                }
                if (content instanceof MimeMultipart)
                    mbp.setContent((MimeMultipart) content);
                else
                    mbp.setDataHandler(new DataHandler(content, contentType));
                mp.addBodyPart(mbp);
            }

        } //end if, adding old attachments

        if (newAttach > 0) { //if there are new attachments
            // create the parts with the attachments
            MimeBodyPart[] mbps = new MimeBodyPart[newAttach];

            for (int e = 0; e < newAttach; e++) {
                mbps[e] = new MimeBodyPart();

                // attach the file to the message
                JsAttachment attach = (JsAttachment) attachments.get(e);
                UploadedFile upfile = getUploadedFile(attach.uploadId);
                FileDataSource fds = new FileDataSource(upfile.getFile());
                mbps[e].setDataHandler(new DataHandler(fds));
                // filename starts has format:
                // "_" + userid + sessionId + "_" + filename
                //
                if (attach.inline) {
                    mbps[e].setDisposition(Part.INLINE);
                }
                String contentFileName = attach.fileName.trim();
                mbps[e].setFileName(contentFileName);
                String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\"";
                mbps[e].setHeader("Content-type", contentType);
                if (attach.cid != null && attach.cid.trim().length() > 0) {
                    mbps[e].setHeader("Content-ID", "<" + attach.cid + ">");
                    mbps[e].setHeader("X-Attachment-Id", attach.cid);
                    mbps[e].setDisposition(Part.INLINE);
                    if (unrelated == null)
                        unrelated = new MimeMultipart("mixed");
                }
            } //end for e

            //add the new attachment parts
            if (unrelated == null) {
                for (int r = 0; r < newAttach; r++)
                    mp.addBodyPart(mbps[r]);
            } else {
                //mp becomes the related part with text parts and cids
                MimeMultipart related = mp;
                related.setSubType("related");
                //nest the related part into the mixed part
                mp = unrelated;
                MimeBodyPart mbd = new MimeBodyPart();
                mbd.setContent(related);
                mp.addBodyPart(mbd);
                for (int r = 0; r < newAttach; r++) {
                    if (mbps[r].getHeader("Content-ID") != null) {
                        related.addBodyPart(mbps[r]);
                    } else {
                        mp.addBodyPart(mbps[r]);
                    }
                }
            }

        } //end if, adding new attachments

        //
        //          msg.addHeaderLine("This is a multi-part message in MIME format.");
        // add the Multipart to the message
        msg.setContent(mp);

    } else { //end if newattach
        msg.setText(smsg.getContent());
    } //singlepart message

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

    return msg;

}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

@Override
public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject,
        String body, List<File> attachments, MailerResult result) {

    try {/*  w  w  w .  j  a  v a  2 s .  c o  m*/
        //   see FXOLAT-74: send all mails as <fromemail> (in config) to have a valid reverse lookup and therefore pass spam protection.
        // following doesn't work correctly, therefore add bounce-address in message already
        Address convertedFrom = getRawEmailFromAddress(from);
        MimeMessage msg = createMessage(convertedFrom);
        Address viewableFrom = createAddressWithName(WebappHelper.getMailConfig("mailFrom"),
                WebappHelper.getMailConfig("mailFromName"));
        msg.setFrom(viewableFrom);
        msg.setSubject(subject, "utf-8");
        // reply to can only be an address without name (at least for postfix!), see FXOLAT-312
        msg.setReplyTo(new Address[] { convertedFrom });

        if (tos != null && tos.length > 0) {
            msg.addRecipients(RecipientType.TO, tos);
        }

        if (ccs != null && ccs.length > 0) {
            msg.addRecipients(RecipientType.CC, ccs);
        }

        if (bccs != null && bccs.length > 0) {
            msg.addRecipients(RecipientType.BCC, bccs);
        }

        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart("mixed");
            // 1) add body part
            if (StringHelper.isHtml(body)) {
                Multipart alternativePart = createMultipartAlternative(body);
                MimeBodyPart wrap = new MimeBodyPart();
                wrap.setContent(alternativePart);
                multipart.addBodyPart(wrap);
            } else {
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(body);
                multipart.addBodyPart(messageBodyPart);
            }

            // 2) add attachments
            for (File attachmentFile : attachments) {
                // abort if attachment does not exist
                if (attachmentFile == null || !attachmentFile.exists()) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    logError("Tried to send mail wit attachment that does not exist::"
                            + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null);
                    return msg;
                }
                BodyPart filePart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachmentFile);
                filePart.setDataHandler(new DataHandler(source));
                filePart.setFileName(attachmentFile.getName());
                multipart.addBodyPart(filePart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            if (StringHelper.isHtml(body)) {
                msg.setContent(createMultipartAlternative(body));
            } else {
                msg.setText(body, "utf-8");
            }
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (AddressException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        logError("", e);
        return null;
    } catch (MessagingException e) {
        result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
        logError("", e);
        return null;
    } catch (UnsupportedEncodingException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        logError("", e);
        return null;
    }
}

From source file:org.kuali.test.utils.Utils.java

/**
 * /*from w  w w.  ja va2 s  .  c o  m*/
 * @param configuration
 * @param overrideEmail
 * @param testSuite
 * @param testHeader
 * @param testResults
 * @param errorCount
 * @param warningCount
 * @param successCount 
 */
public static void sendMail(KualiTestConfigurationDocument.KualiTestConfiguration configuration,
        String overrideEmail, TestSuite testSuite, TestHeader testHeader, List<File> testResults,
        int errorCount, int warningCount, int successCount) {

    if (StringUtils.isNotBlank(configuration.getEmailSetup().getFromAddress())
            && StringUtils.isNotBlank(configuration.getEmailSetup().getMailHost())) {

        String[] toAddresses = getEmailToAddresses(configuration, testSuite, testHeader);

        if (toAddresses.length > 0) {
            Properties props = new Properties();
            props.put("mail.smtp.host", configuration.getEmailSetup().getMailHost());
            Session session = Session.getDefaultInstance(props, null);

            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress(configuration.getEmailSetup().getFromAddress()));

                if (StringUtils.isBlank(overrideEmail)) {
                    for (String recipient : toAddresses) {
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
                    }
                } else {
                    StringTokenizer st = new StringTokenizer(overrideEmail, ",");
                    while (st.hasMoreTokens()) {
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(st.nextToken()));
                    }
                }

                StringBuilder subject = new StringBuilder(configuration.getEmailSetup().getSubject());
                subject.append(" - Platform: ");
                if (testSuite != null) {
                    subject.append(testSuite.getPlatformName());
                    subject.append(", TestSuite: ");
                    subject.append(testSuite.getName());
                } else {
                    subject.append(testHeader.getPlatformName());
                    subject.append(", Test: ");
                    subject.append(testHeader.getTestName());
                }

                subject.append(" - [errors=");
                subject.append(errorCount);
                subject.append(", warnings=");
                subject.append(warningCount);
                subject.append(", successes=");
                subject.append(successCount);
                subject.append("]");

                msg.setSubject(subject.toString());

                StringBuilder msgtxt = new StringBuilder(256);
                msgtxt.append("Please see test output in the following attached files:\n");

                for (File f : testResults) {
                    msgtxt.append(f.getName());
                    msgtxt.append("\n");
                }

                // create and fill the first message part
                MimeBodyPart mbp1 = new MimeBodyPart();
                mbp1.setText(msgtxt.toString());

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

                for (File f : testResults) {
                    if (f.exists() && f.isFile()) {
                        // create the second message part
                        MimeBodyPart mbp2 = new MimeBodyPart();

                        // attach the file to the message
                        mbp2.setDataHandler(new DataHandler(new FileDataSource(f)));
                        mbp2.setFileName(f.getName());
                        mp.addBodyPart(mbp2);
                    }
                }

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

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

                Transport.send(msg);
            } catch (MessagingException ex) {
                LOG.warn(ex.toString(), ex);
            }
        }
    }
}

From source file:Implement.Service.ProviderServiceImpl.java

@Override
public boolean sendMail(HttpServletRequest request, String providerName, int providerID, String baseUrl)
        throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtpm.csloxinfo.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*  w ww.j  a v  a  2  s.  c  o m*/
    });

    //Create data for referral
    java.util.Date date = new java.util.Date();
    String s = providerID + (new Timestamp(date.getTime()).toString());
    MessageDigest m = null;
    try {
        m = MessageDigest.getInstance("MD5");

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ProviderServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    m.update(s.getBytes(), 0, s.length());
    String md5 = (new BigInteger(1, m.digest()).toString(16));

    String title = "You have an invitation from your friend.";
    String receiver = request.getParameter("email");

    //        StringBuilder messageContentHtml = new StringBuilder();
    //        messageContentHtml.append(request.getParameter("message") + "<br />\n");
    //        messageContentHtml.append("You can become a provider from here:  " + baseUrl + "/Common/Provider/SignupReferral/" + md5);
    //        String messageContent = messageContentHtml.toString();
    String emailContent = "  <div style='background: url(cid:bg_Icon) no-repeat;background-color:#ebebec;text-align: center;width:610px;height:365px'>"
            + "            <p style='font-size:16px;padding-top: 45px; padding-bottom: 15px;'>Your friend <b>"
            + providerName + "</b> has invited you to complete purchase via</p>"
            + "            <a href='http://youtripper.com/Common/Provider/SignupReferral/" + md5
            + "' style='width: 160px;height: 50px;border-radius: 5px;border: 0;"
            + "                    background-color: #ff514e;font-size: 14px;font-weight: bolder;color: #fff;display: block;line-height: 50px;margin: 0 auto;text-decoration:none;' >Refferal Link</a>"
            + "            <p style='font-size:16px;margin:30px;'><b>" + providerName
            + "</b> will get 25 credit</p>"
            + "            <a href='http://youtripper.com' target='_blank'><img src='cid:gift_Icon' width='90' height='90'></a>"
            + "            <a href='http://youtripper.com' target='_blank' style='font-size:10px;color:#939598;text-decoration:none'><p>from www.youtripper.com</p></a>"
            + "            " + "            " + "        </div>";

    String path = System.getProperty("catalina.base");
    MimeBodyPart backgroundImage = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png"));
    backgroundImage.setDataHandler(new DataHandler(source));
    backgroundImage.setFileName("backgroundImage.png");
    backgroundImage.setDisposition(MimeBodyPart.INLINE);
    backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid

    MimeBodyPart giftImage = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png"));
    giftImage.setDataHandler(new DataHandler(source));
    giftImage.setFileName("emailGift.png");
    giftImage.setDisposition(MimeBodyPart.INLINE);
    giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(emailContent, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);
    mp.addBodyPart(backgroundImage);
    mp.addBodyPart(giftImage);
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
    message.setSubject(title);
    message.setContent(mp);
    message.saveChanges();
    Transport.send(message);

    ReferralDTO referral = new ReferralDTO(providerID, receiver, String.valueOf(System.currentTimeMillis()),
            md5, 0);
    referralDAO.insertNewReferral(referral);
    return true;
}

From source file:Implement.Service.ProviderServiceImpl.java

@Override
public boolean sendEmailReferral(String data, int providerID, String baseUrl) throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from   w w w  . j  a  va2s .  co  m
    });

    String title = "You have an invitation from your friend.";

    JsonObject jsonObject = gson.fromJson(data, JsonObject.class);
    String content = jsonObject.get("content").getAsString();
    JsonArray sportsArray = jsonObject.get("emails").getAsJsonArray();
    ArrayList<String> listEmail = new ArrayList<>();
    if (sportsArray != null) {
        for (int i = 0; i < sportsArray.size(); i++) {
            listEmail.add(sportsArray.get(i).getAsString());
        }
    }

    String path = System.getProperty("catalina.base");
    MimeBodyPart backgroundImage = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png"));
    backgroundImage.setDataHandler(new DataHandler(source));
    backgroundImage.setFileName("backgroundImage.png");
    backgroundImage.setDisposition(MimeBodyPart.INLINE);
    backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid

    MimeBodyPart giftImage = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png"));
    giftImage.setDataHandler(new DataHandler(source));
    giftImage.setFileName("emailGift.png");
    giftImage.setDisposition(MimeBodyPart.INLINE);
    giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    String addresses = "";
    for (int i = 0; i < listEmail.size(); i++) {
        if (i < listEmail.size() - 1) {
            addresses = addresses + listEmail.get(i) + ",";
        } else {
            addresses = addresses + listEmail.get(i);
        }
    }

    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses));

    message.setSubject(title);
    message.setContent(mp);
    message.saveChanges();
    try {
        Transport.send(message);
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("sent");
    return true;
}