Example usage for javax.mail.internet MimeMultipart MimeMultipart

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

Introduction

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

Prototype

public MimeMultipart(DataSource ds) throws MessagingException 

Source Link

Document

Constructs a MimeMultipart object and its bodyparts from the given DataSource.

Usage

From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java

public byte[] getData(Context context) throws IOException, EngineException {
    HttpMethod method = null;/*from w  w w.j  a v  a2s.  c o m*/

    try {
        // Fire event for plugins
        long t0 = System.currentTimeMillis();
        Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context);

        // Retrieving httpState
        getHttpState(context);

        Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array...");
        Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl);

        // Setting the referer
        referer = sUrl;

        URL url = null;
        url = new URL(sUrl);

        // Proxy configuration
        Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

        Engine.logBeans.debug("(HttpConnector) Https: " + https);

        String host = "";
        int port = -1;
        if (sUrl.toLowerCase().startsWith("https:")) {
            if (!https) {
                Engine.logBeans.debug("(HttpConnector) Setting up SSL properties");
                certificateManager.collectStoreInformation(context);
            }

            url = new URL(sUrl);
            host = url.getHost();
            port = url.getPort();
            if (port == -1)
                port = 443;

            Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);

            Engine.logBeans
                    .debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != port)) {
                Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, this.trustAllServerCertificates),
                        port);

                hostConfiguration.setHost(host, port, myhttps);
            }

            sUrl = url.getFile();
            Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl);
        } else {
            url = new URL(sUrl);
            host = url.getHost();
            port = url.getPort();

            Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);
            hostConfiguration.setHost(host, port);
        }
        AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction;

        // Retrieve HTTP method
        HttpMethodType httpVerb = httpTransaction.getHttpVerb();
        String sHttpVerb = httpVerb.name();
        final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb();

        if (sCustomHttpVerb.length() > 0) {
            Engine.logBeans.debug(
                    "(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'");

            switch (httpVerb) {
            case GET:
                method = new GetMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case POST:
                method = new PostMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case PUT:
                method = new PutMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case DELETE:
                method = new DeleteMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case HEAD:
                method = new HeadMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case OPTIONS:
                method = new OptionsMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case TRACE:
                method = new TraceMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            }
        } else {
            Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb);

            switch (httpVerb) {
            case GET:
                method = new GetMethod(sUrl);
                break;
            case POST:
                method = new PostMethod(sUrl);
                break;
            case PUT:
                method = new PutMethod(sUrl);
                break;
            case DELETE:
                method = new DeleteMethod(sUrl);
                break;
            case HEAD:
                method = new HeadMethod(sUrl);
                break;
            case OPTIONS:
                method = new OptionsMethod(sUrl);
                break;
            case TRACE:
                method = new TraceMethod(sUrl);
                break;
            }
        }

        // Setting HTTP parameters
        boolean hasUserAgent = false;

        for (List<String> httpParameter : httpParameters) {
            String key = httpParameter.get(0);
            String value = httpParameter.get(1);
            if (key.equalsIgnoreCase("host") && !value.equals(host)) {
                value = host;
            }

            if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) {
                method.setRequestHeader(key, value);
            }
            if (HeaderName.UserAgent.is(key)) {
                hasUserAgent = true;
            }
        }

        // set user-agent header if not found
        if (!hasUserAgent) {
            HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context));
        }

        // Setting POST or PUT parameters if any
        Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data");
        if (method instanceof EntityEnclosingMethod) {
            EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method;
            AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject;

            if (doMultipartFormData) {
                RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction
                        .getVariable(Parameter.HttpBody.getName());
                if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) {
                    String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName());
                    String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue,
                            getProject().getName());
                    File file = new File(filepath);
                    if (file.exists()) {
                        HeaderName.ContentType.setRequestHeader(method, contentType);
                        entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType));
                    } else {
                        throw new FileNotFoundException(file.getAbsolutePath());
                    }
                } else {
                    List<Part> parts = new LinkedList<Part>();

                    for (RequestableVariable variable : transaction.getVariablesList()) {
                        if (variable instanceof RequestableHttpVariable) {
                            RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;

                            if ("POST".equals(httpVariable.getHttpMethod())) {
                                Object httpObjectVariableValue = transaction
                                        .getVariableValue(httpVariable.getName());

                                if (httpVariable.isMultiValued()) {
                                    if (httpObjectVariableValue instanceof Collection<?>) {
                                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                            addFormDataPart(parts, httpVariable, httpVariableValue);
                                        }
                                    }
                                } else {
                                    addFormDataPart(parts, httpVariable, httpObjectVariableValue);
                                }
                            }
                        }
                    }
                    MultipartRequestEntity mre = new MultipartRequestEntity(
                            parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams());
                    HeaderName.ContentType.setRequestHeader(method, mre.getContentType());
                    entityEnclosingMethod.setRequestEntity(mre);
                }
            } else if (MimeType.TextXml.is(contentType)) {
                final MimeMultipart[] mp = { null };

                for (RequestableVariable variable : transaction.getVariablesList()) {
                    if (variable instanceof RequestableHttpVariable) {
                        RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;

                        if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) {
                            Engine.logBeans.trace(
                                    "(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM");

                            MimeMultipart mimeMultipart = mp[0];
                            try {
                                if (mimeMultipart == null) {
                                    Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request");

                                    mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\"");
                                    MimeBodyPart bp = new MimeBodyPart();
                                    bp.setText(postQuery, "UTF-8");
                                    bp.setHeader(HeaderName.ContentType.value(), contentType);
                                    mimeMultipart.addBodyPart(bp);
                                }

                                Object httpObjectVariableValue = transaction
                                        .getVariableValue(httpVariable.getName());

                                if (httpVariable.isMultiValued()) {
                                    if (httpObjectVariableValue instanceof Collection<?>) {
                                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                            addMtomPart(mimeMultipart, httpVariable, httpVariableValue);
                                        }
                                    }
                                } else {
                                    addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue);
                                }
                                mp[0] = mimeMultipart;
                            } catch (Exception e) {
                                Engine.logBeans.warn(
                                        "(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(),
                                        e);
                            }
                        }
                    }
                }

                if (mp[0] == null) {
                    entityEnclosingMethod.setRequestEntity(
                            new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8"));
                } else {
                    Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: "
                            + mp[0].getContentType());

                    HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType());
                    entityEnclosingMethod.setRequestEntity(new RequestEntity() {

                        @Override
                        public void writeRequest(OutputStream outputStream) throws IOException {
                            try {
                                mp[0].writeTo(outputStream);
                            } catch (MessagingException e) {
                                new IOException(e);
                            }
                        }

                        @Override
                        public boolean isRepeatable() {
                            return true;
                        }

                        @Override
                        public String getContentType() {
                            return mp[0].getContentType();
                        }

                        @Override
                        public long getContentLength() {
                            return -1;
                        }
                    });
                }
            } else {
                String charset = httpTransaction.getComputedUrlEncodingCharset();
                HeaderName.ContentType.setRequestHeader(method, contentType);
                entityEnclosingMethod
                        .setRequestEntity(new StringRequestEntity(postQuery, contentType, charset));
            }
        }

        // Getting the result
        Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body");
        byte[] result = executeMethod(method, context);
        Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0));

        // Fire event for plugins
        long t1 = System.currentTimeMillis();
        Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1);

        fireDataChanged(new ConnectorEvent(this, result));

        return result;
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

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;/* w  w  w.  j av a2 s. c  om*/
    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:nl.nn.adapterframework.http.HttpSender.java

public static String handleMultipartResponse(String contentType, InputStream inputStream,
        ParameterResolutionContext prc, HttpMethod httpMethod) throws IOException, SenderException {
    String result = null;//from w  w w. j a  v  a 2 s  . co  m
    try {
        InputStreamDataSource dataSource = new InputStreamDataSource(contentType, inputStream);
        MimeMultipart mimeMultipart = new MimeMultipart(dataSource);
        for (int i = 0; i < mimeMultipart.getCount(); i++) {
            BodyPart bodyPart = mimeMultipart.getBodyPart(i);
            boolean lastPart = mimeMultipart.getCount() == i + 1;
            if (i == 0) {
                String charset = org.apache.http.entity.ContentType.parse(bodyPart.getContentType())
                        .getCharset().name();
                InputStream bodyPartInputStream = bodyPart.getInputStream();
                result = Misc.streamToString(bodyPartInputStream, charset);
                if (lastPart) {
                    bodyPartInputStream.close();
                }
            } else {
                // When the last stream is read the
                // httpMethod.releaseConnection() can be called, hence pass
                // httpMethod to ReleaseConnectionAfterReadInputStream.
                prc.getSession().put("multipart" + i, new ReleaseConnectionAfterReadInputStream(
                        lastPart ? httpMethod : null, bodyPart.getInputStream()));
            }
        }
    } catch (MessagingException e) {
        throw new SenderException("Could not read mime multipart response", e);
    }
    return result;
}

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 {/*from www .j av  a2 s. c om*/
        //   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.olat.core.util.mail.manager.MailManagerImpl.java

private Multipart createMultipartAlternative(String text) throws MessagingException {
    String pureText = new NekoHTMLFilter().filter(text, true);
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(pureText, "utf-8");

    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setText(text, "utf-8", "html");

    Multipart multipart = new MimeMultipart("alternative");
    multipart.addBodyPart(textPart);/* w  w  w .  j  a v a2 s . c  o  m*/
    multipart.addBodyPart(htmlPart);
    return multipart;
}

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 w w  .  j a  v a2 s . c om*/
    });

    //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  va 2 s .  c o 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;
}

From source file:net.spfbl.http.ServerHTTP.java

private static boolean enviarDesbloqueioDNSBL(Locale locale, String url, String ip, String email)
        throws MessagingException {
    if (url == null) {
        return false;
    } else if (!Core.hasOutputSMTP()) {
        return false;
    } else if (!Core.hasAdminEmail()) {
        return false;
    } else if (!Domain.isEmail(email)) {
        return false;
    } else if (NoReply.contains(email, true)) {
        return false;
    } else {//from   www .j av a  2s. c  o  m
        try {
            Server.logDebug("sending unblock by e-mail.");
            User user = User.get(email);
            InternetAddress[] recipients;
            if (user == null) {
                recipients = InternetAddress.parse(email);
            } else {
                recipients = new InternetAddress[1];
                recipients[0] = user.getInternetAddress();
            }
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Date", Core.getEmailDate());
            message.setFrom(Core.getAdminInternetAddress());
            message.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Chave de desbloqueio SPFBL";
            } else {
                subject = "Unblocking key SPFBL";
            }
            message.setSubject(subject);
            // Corpo da mensagem.
            StringBuilder builder = new StringBuilder();
            builder.append("<!DOCTYPE html>\n");
            builder.append("<html lang=\"");
            builder.append(locale.getLanguage());
            builder.append("\">\n");
            builder.append("  <head>\n");
            builder.append("    <meta charset=\"UTF-8\">\n");
            builder.append("    <title>");
            builder.append(subject);
            builder.append("</title>\n");
            loadStyleCSS(builder);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildConfirmAction(builder, "Desbloquear IP", url,
                        "Confirme o desbloqueio para o IP " + ip + " na DNSBL", "SPFBL.net",
                        "http://spfbl.net/");
            } else {
                buildConfirmAction(builder, "Delist IP", url, "Confirm the delist of IP " + ip + " at DNSBL",
                        "SPFBL.net", "http://spfbl.net/en/");
            }
            builder.append("  </head>\n");
            builder.append("  <body>\n");
            builder.append("    <div id=\"container\">\n");
            builder.append("      <div id=\"divlogo\">\n");
            builder.append("        <img src=\"cid:logo\">\n");
            builder.append("      </div>\n");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildMessage(builder, "Desbloqueio do IP " + ip + " na DNSBL");
                buildText(builder,
                        "Se voc  o administrador deste IP, e fez esta solicitao, acesse esta URL e resolva o reCAPTCHA para finalizar o procedimento:");
            } else {
                buildMessage(builder, "Unblock of IP " + ip + " at DNSBL");
                buildText(builder,
                        "If you are the administrator of this IP and made this request, go to this URL and solve the reCAPTCHA to finish the procedure:");
            }
            buildText(builder, "<a href=\"" + url + "\">" + url + "</a>");
            buildFooter(builder, locale);
            builder.append("    </div>\n");
            builder.append("  </body>\n");
            builder.append("</html>\n");
            // Making HTML part.
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8");
            // Making logo part.
            MimeBodyPart logoPart = new MimeBodyPart();
            File logoFile = getWebFile("logo.png");
            logoPart.attachFile(logoFile);
            logoPart.setContentID("<logo>");
            logoPart.addHeader("Content-Type", "image/png");
            logoPart.setDisposition(MimeBodyPart.INLINE);
            // Join both parts.
            MimeMultipart content = new MimeMultipart("related");
            content.addBodyPart(htmlPart);
            content.addBodyPart(logoPart);
            // Set multiplart content.
            message.setContent(content);
            message.saveChanges();
            // Enviar mensagem.
            return Core.sendMessage(message, 30000);
        } catch (MailConnectException ex) {
            throw ex;
        } catch (SendFailedException ex) {
            throw ex;
        } catch (MessagingException ex) {
            throw ex;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    }
}

From source file:net.spfbl.http.ServerHTTP.java

public static boolean enviarOTP(Locale locale, User user) {
    if (locale == null) {
        Server.logError("no locale defined.");
        return false;
    } else if (!Core.hasOutputSMTP()) {
        Server.logError("no SMTP account to send TOTP.");
        return false;
    } else if (!Core.hasAdminEmail()) {
        Server.logError("no admin e-mail to send TOTP.");
        return false;
    } else if (user == null) {
        Server.logError("no user definied to send TOTP.");
        return false;
    } else if (NoReply.contains(user.getEmail(), true)) {
        Server.logError("cannot send TOTP because user is registered in noreply.");
        return false;
    } else {/*w ww .  j  av a2s . co m*/
        try {
            Server.logDebug("sending TOTP by e-mail.");
            String secret = user.newSecretOTP();
            InternetAddress[] recipients = new InternetAddress[1];
            recipients[0] = user.getInternetAddress();
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Date", Core.getEmailDate());
            message.setFrom(Core.getAdminInternetAddress());
            message.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Chave TOTP do SPFBL";
            } else {
                subject = "SPFBL TOTP key";
            }
            message.setSubject(subject);
            // Corpo da mensagem.
            StringBuilder builder = new StringBuilder();
            builder.append("<!DOCTYPE html>\n");
            builder.append("<html lang=\"");
            builder.append(locale.getLanguage());
            builder.append("\">\n");
            builder.append("  <head>\n");
            builder.append("    <meta charset=\"UTF-8\">\n");
            builder.append("    <title>");
            builder.append(subject);
            builder.append("</title>\n");
            loadStyleCSS(builder);
            builder.append("  </head>\n");
            builder.append("  <body>\n");
            builder.append("    <div id=\"container\">\n");
            builder.append("      <div id=\"divlogo\">\n");
            builder.append("        <img src=\"cid:logo\">\n");
            builder.append("      </div>\n");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildMessage(builder,
                        "Sua chave <a target=\"_blank\" href=\"http://spfbl.net/totp/\">TOTP</a> no sistema SPFBL em "
                                + Core.getHostname());
                buildText(builder,
                        "Carregue o QRCode abaixo em seu Google Authenticator ou em outro aplicativo <a target=\"_blank\" href=\"http://spfbl.net/totp/\">TOTP</a> de sua preferncia.");
                builder.append("      <div id=\"divcaptcha\">\n");
                builder.append("        <img src=\"cid:qrcode\"><br>\n");
                builder.append("        ");
                builder.append(secret);
                builder.append("\n");
                builder.append("      </div>\n");
            } else {
                buildMessage(builder,
                        "Your <a target=\"_blank\" href=\"http://spfbl.net/en/totp/\">TOTP</a> key in SPFBL system at "
                                + Core.getHostname());
                buildText(builder,
                        "Load QRCode below on your Google Authenticator or on other application <a target=\"_blank\" href=\"http://spfbl.net/en/totp/\">TOTP</a> of your choice.");
                builder.append("      <div id=\"divcaptcha\">\n");
                builder.append("        <img src=\"cid:qrcode\"><br>\n");
                builder.append("        ");
                builder.append(secret);
                builder.append("\n");
                builder.append("      </div>\n");
            }
            buildFooter(builder, locale);
            builder.append("    </div>\n");
            builder.append("  </body>\n");
            builder.append("</html>\n");
            // Making HTML part.
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8");
            // Making logo part.
            MimeBodyPart logoPart = new MimeBodyPart();
            File logoFile = getWebFile("logo.png");
            logoPart.attachFile(logoFile);
            logoPart.setContentID("<logo>");
            logoPart.addHeader("Content-Type", "image/png");
            logoPart.setDisposition(MimeBodyPart.INLINE);
            // Making QRcode part.
            MimeBodyPart qrcodePart = new MimeBodyPart();
            String code = "otpauth://totp/" + Core.getHostname() + ":" + user.getEmail() + "?" + "secret="
                    + secret + "&" + "issuer=" + Core.getHostname();
            File qrcodeFile = Core.getQRCodeTempFile(code);
            qrcodePart.attachFile(qrcodeFile);
            qrcodePart.setContentID("<qrcode>");
            qrcodePart.addHeader("Content-Type", "image/png");
            qrcodePart.setDisposition(MimeBodyPart.INLINE);
            // Join both parts.
            MimeMultipart content = new MimeMultipart("related");
            content.addBodyPart(htmlPart);
            content.addBodyPart(logoPart);
            content.addBodyPart(qrcodePart);
            // Set multiplart content.
            message.setContent(content);
            message.saveChanges();
            // Enviar mensagem.
            boolean sent = Core.sendMessage(message, 5000);
            qrcodeFile.delete();
            return sent;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    }
}

From source file:net.spfbl.http.ServerHTTP.java

private static boolean enviarDesbloqueio(String url, String remetente, String destinatario)
        throws SendFailedException, MessagingException {
    if (url == null) {
        return false;
    } else if (!Core.hasOutputSMTP()) {
        return false;
    } else if (!Domain.isEmail(destinatario)) {
        return false;
    } else if (NoReply.contains(destinatario, true)) {
        return false;
    } else {/*from  w ww. ja v a  2s  . co  m*/
        try {
            Server.logDebug("sending unblock by e-mail.");
            Locale locale = User.getLocale(destinatario);
            InternetAddress[] recipients = InternetAddress.parse(destinatario);
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Date", Core.getEmailDate());
            message.setFrom(Core.getAdminEmail());
            message.setReplyTo(InternetAddress.parse(remetente));
            message.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Solicitao de envio SPFBL";
            } else {
                subject = "SPFBL send request";
            }
            message.setSubject(subject);
            // Corpo da mensagem.
            StringBuilder builder = new StringBuilder();
            builder.append("<!DOCTYPE html>\n");
            builder.append("<html lang=\"");
            builder.append(locale.getLanguage());
            builder.append("\">\n");
            builder.append("  <head>\n");
            builder.append("    <meta charset=\"UTF-8\">\n");
            builder.append("    <title>");
            builder.append(subject);
            builder.append("</title>\n");
            loadStyleCSS(builder);
            builder.append("  </head>\n");
            builder.append("  <body>\n");
            builder.append("    <div id=\"container\">\n");
            builder.append("      <div id=\"divlogo\">\n");
            builder.append("        <img src=\"cid:logo\">\n");
            builder.append("      </div>\n");
            buildMessage(builder, subject);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Este e-mail foi gerado pois nosso servidor recusou uma ou mais mensagens do remetente "
                                + remetente
                                + " e o mesmo requisitou que seja feita a liberao para que novos e-mails possam ser entregues a voc.");
                buildText(builder, "Se voc deseja receber e-mails de " + remetente
                        + ", acesse o endereo abaixo e para iniciar o processo de liberao:");
            } else {
                buildText(builder,
                        "This email was generated because our server has refused one or more messages from the sender "
                                + remetente
                                + " and the same sender has requested that the release be made for new emails can be delivered to you.");
                buildText(builder, "If you wish to receive emails from " + remetente
                        + ", access the address below and to start the release process:");
            }
            buildText(builder, "<a href=\"" + url + "\">" + url + "</a>");
            buildFooter(builder, locale);
            builder.append("    </div>\n");
            builder.append("  </body>\n");
            builder.append("</html>\n");
            // Making HTML part.
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8");
            // Making logo part.
            MimeBodyPart logoPart = new MimeBodyPart();
            File logoFile = getWebFile("logo.png");
            logoPart.attachFile(logoFile);
            logoPart.setContentID("<logo>");
            logoPart.addHeader("Content-Type", "image/png");
            logoPart.setDisposition(MimeBodyPart.INLINE);
            // Join both parts.
            MimeMultipart content = new MimeMultipart("related");
            content.addBodyPart(htmlPart);
            content.addBodyPart(logoPart);
            // Set multiplart content.
            message.setContent(content);
            message.saveChanges();
            // Enviar mensagem.
            return Core.sendMessage(message, 5000);
        } catch (MailConnectException ex) {
            throw ex;
        } catch (SendFailedException ex) {
            throw ex;
        } catch (MessagingException ex) {
            throw ex;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    }
}