Example usage for javax.mail.internet MimeMessage saveChanges

List of usage examples for javax.mail.internet MimeMessage saveChanges

Introduction

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

Prototype

@Override
public void saveChanges() throws MessagingException 

Source Link

Document

Updates the appropriate header fields of this message to be consistent with the message's contents.

Usage

From source file:net.spfbl.spf.SPF.java

private static boolean enviarLiberacao(String url, String remetente, String destinatario) {
    if (Core.hasOutputSMTP() && Core.hasAdminEmail() && Domain.isValidEmail(remetente)
            && Domain.isValidEmail(destinatario) && url != null && !NoReply.contains(remetente, true)) {
        try {//from  w ww . j a v a 2  s .c om
            Server.logDebug("sending liberation by e-mail.");
            Locale locale = Core.getDefaultLocale(remetente);
            InternetAddress[] recipients = InternetAddress.parse(remetente);
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Date", Core.getEmailDate());
            message.setFrom(Core.getAdminEmail());
            message.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Liberao de recebimento";
            } else {
                subject = "Receiving release";
            }
            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");
            ServerHTTP.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");
            ServerHTTP.buildMessage(builder, subject);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                ServerHTTP.buildText(builder, "O recebimento da sua mensagem para " + destinatario
                        + " est sendo atrasado por suspeita de SPAM.");
                ServerHTTP.buildText(builder,
                        "Para que sua mensagem seja liberada, acesse este link e resolva o desafio reCAPTCHA:");
            } else {
                ServerHTTP.buildText(builder, "Receiving your message to " + destinatario
                        + " is being delayed due to suspected SPAM.");
                ServerHTTP.buildText(builder,
                        "In order for your message to be released, access this link and resolve the reCAPTCHA:");
            }
            ServerHTTP.buildText(builder, "<a href=\"" + url + "\">" + url + "</a>");
            ServerHTTP.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 = ServerHTTP.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) {
            return false;
        } catch (SendFailedException ex) {
            return false;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    } else {
        return false;
    }
}

From source file:net.wastl.webmail.plugins.SendMessage.java

public HTMLDocument handleURL(String suburl, HTTPSession sess1, HTTPRequestHeader head)
        throws WebMailException, ServletException {
    if (sess1 == null) {
        throw new WebMailException(
                "No session was given. If you feel this is incorrect, please contact your system administrator");
    }//from   w  ww .  j av a  2  s .  c  om
    WebMailSession session = (WebMailSession) sess1;
    UserData user = session.getUser();
    HTMLDocument content;

    Locale locale = user.getPreferredLocale();

    /* Save message in case there is an error */
    session.storeMessage(head);

    if (head.isContentSet("SEND")) {
        /* The form was submitted, now we will send it ... */
        try {
            MimeMessage msg = new MimeMessage(mailsession);

            Address from[] = new Address[1];
            try {
                /**
                 * Why we need
                 * org.bulbul.util.TranscodeUtil.transcodeThenEncodeByLocale()?
                 *
                 * Because we specify client browser's encoding to UTF-8, IE seems
                 * to send all data encoded in UTF-8. We have to transcode all byte
                 * sequences we received to UTF-8, and next we encode those strings
                 * using MimeUtility.encodeText() depending on user's locale. Since
                 * MimeUtility.encodeText() is used to convert the strings into its
                 * transmission format, finally we can use the strings in the
                 * outgoing e-mail which relies on receiver's email agent to decode
                 * the strings.
                 *
                 * As described in JavaMail document, MimeUtility.encodeText() conforms
                 * to RFC2047 and as a result, we'll get strings like "=?Big5?B......".
                 */
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // from[0]=new InternetAddress(MimeUtility.encodeText(session.getUser().getEmail()),
                //                  MimeUtility.encodeText(session.getUser().getFullName()));
                from[0] = new InternetAddress(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("FROM"), null, locale),
                        TranscodeUtil.transcodeThenEncodeByLocale(session.getUser().getFullName(), null,
                                locale));
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                from[0] = new InternetAddress(head.getContent("FROM"), session.getUser().getFullName());
            }

            StringTokenizer t;
            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("TO")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("TO"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("TO").trim(), ",;");
            }

            /* Check To: field, when empty, throw an exception */
            if (t.countTokens() < 1) {
                throw new MessagingException("The recipient field must not be empty!");
            }
            Address to[] = new Address[t.countTokens()];
            int i = 0;
            while (t.hasMoreTokens()) {
                to[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("CC")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("CC"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("CC").trim(), ",;");
            }
            Address cc[] = new Address[t.countTokens()];
            i = 0;
            while (t.hasMoreTokens()) {
                cc[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("BCC")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("BCC"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("BCC").trim(), ",;");
            }
            Address bcc[] = new Address[t.countTokens()];
            i = 0;
            while (t.hasMoreTokens()) {
                bcc[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            session.setSent(false);

            msg.addFrom(from);
            if (to.length > 0) {
                msg.addRecipients(Message.RecipientType.TO, to);
            }
            if (cc.length > 0) {
                msg.addRecipients(Message.RecipientType.CC, cc);
            }
            if (bcc.length > 0) {
                msg.addRecipients(Message.RecipientType.BCC, bcc);
            }
            msg.addHeader("X-Mailer",
                    WebMailServer.getVersion() + ", " + getName() + " plugin v" + getVersion());

            String subject = null;

            if (!head.isContentSet("SUBJECT")) {
                subject = "no subject";
            } else {
                try {
                    // subject=MimeUtility.encodeText(head.getContent("SUBJECT"));
                    subject = TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("SUBJECT"), "ISO8859_1",
                            locale);
                } catch (UnsupportedEncodingException e) {
                    log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                    subject = head.getContent("SUBJECT");
                }
            }

            msg.addHeader("Subject", subject);

            if (head.isContentSet("REPLY-TO")) {
                // msg.addHeader("Reply-To",head.getContent("REPLY-TO"));
                msg.addHeader("Reply-To", TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("REPLY-TO"),
                        "ISO8859_1", locale));
            }

            msg.setSentDate(new Date(System.currentTimeMillis()));

            String contnt = head.getContent("BODY");

            //String charset=MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset());
            String charset = "utf-8";

            MimeMultipart cont = new MimeMultipart();
            MimeBodyPart txt = new MimeBodyPart();

            // Transcode to UTF-8
            contnt = new String(contnt.getBytes("ISO8859_1"), "UTF-8");
            // Encode text
            if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) {
                txt.setText(contnt, "Big5");
                txt.setHeader("Content-Type", "text/plain; charset=\"Big5\"");
                txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP?
            } else {
                txt.setText(contnt, "utf-8");
                txt.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
                txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP?
            }

            /* Add an advertisement if the administrator requested to do so */
            cont.addBodyPart(txt);
            if (store.getConfig("ADVERTISEMENT ATTACH").equals("YES")) {
                MimeBodyPart adv = new MimeBodyPart();
                String file = "";
                if (store.getConfig("ADVERTISEMENT SIGNATURE PATH").startsWith("/")) {
                    file = store.getConfig("ADVERTISEMENT SIGNATURE PATH");
                } else {
                    file = parent.getProperty("webmail.data.path") + System.getProperty("file.separator")
                            + store.getConfig("ADVERTISEMENT SIGNATURE PATH");
                }
                String advcont = "";
                try {
                    BufferedReader fin = new BufferedReader(new FileReader(file));
                    String line = fin.readLine();
                    while (line != null && !line.equals("")) {
                        advcont += line + "\n";
                        line = fin.readLine();
                    }
                    fin.close();
                } catch (IOException ex) {
                }

                /**
                 * Transcode to UTF-8; Since advcont comes from file, we transcode
                 * it from default encoding.
                 */
                // Encode text
                if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) {
                    advcont = new String(advcont.getBytes(), "Big5");
                    adv.setText(advcont, "Big5");
                    adv.setHeader("Content-Type", "text/plain; charset=\"Big5\"");
                    adv.setHeader("Content-Transfer-Encoding", "quoted-printable");
                } else {
                    advcont = new String(advcont.getBytes(), "UTF-8");
                    adv.setText(advcont, "utf-8");
                    adv.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
                    adv.setHeader("Content-Transfer-Encoding", "quoted-printable");
                }

                cont.addBodyPart(adv);
            }
            for (String attachmentKey : session.getAttachments().keySet()) {
                ByteStore bs = session.getAttachment(attachmentKey);
                InternetHeaders ih = new InternetHeaders();
                ih.addHeader("Content-Transfer-Encoding", "BASE64");

                PipedInputStream pin = new PipedInputStream();
                PipedOutputStream pout = new PipedOutputStream(pin);

                /* This is used to write to the Pipe asynchronously to avoid blocking */
                StreamConnector sconn = new StreamConnector(pin, (int) (bs.getSize() * 1.6) + 1000);
                BufferedOutputStream encoder = new BufferedOutputStream(MimeUtility.encode(pout, "BASE64"));
                encoder.write(bs.getBytes());
                encoder.flush();
                encoder.close();
                //MimeBodyPart att1=sconn.getResult();
                MimeBodyPart att1 = new MimeBodyPart(ih, sconn.getResult().getBytes());

                if (bs.getDescription() != "") {
                    att1.setDescription(bs.getDescription(), "utf-8");
                }
                /**
                 * As described in FileAttacher.java line #95, now we need to
                 * encode the attachment file name.
                 */
                // att1.setFileName(bs.getName());
                String fileName = bs.getName();
                String localeCharset = getLocaleCharset(locale.getLanguage(), locale.getCountry());
                String encodedFileName = MimeUtility.encodeText(fileName, localeCharset, null);
                if (encodedFileName.equals(fileName)) {
                    att1.addHeader("Content-Type", bs.getContentType());
                    att1.setFileName(fileName);
                } else {
                    att1.addHeader("Content-Type", bs.getContentType() + "; charset=" + localeCharset);
                    encodedFileName = encodedFileName.substring(localeCharset.length() + 5,
                            encodedFileName.length() - 2);
                    encodedFileName = encodedFileName.replace('=', '%');
                    att1.addHeaderLine("Content-Disposition: attachment; filename*=" + localeCharset + "''"
                            + encodedFileName);
                }
                cont.addBodyPart(att1);
            }
            msg.setContent(cont);
            //              }

            msg.saveChanges();

            boolean savesuccess = true;

            msg.setHeader("Message-ID", session.getUserModel().getWorkMessage().getAttribute("msgid"));
            if (session.getUser().wantsSaveSent()) {
                String folderhash = session.getUser().getSentFolder();
                try {
                    Folder folder = session.getFolder(folderhash);
                    Message[] m = new Message[1];
                    m[0] = msg;
                    folder.appendMessages(m);
                } catch (MessagingException e) {
                    savesuccess = false;
                } catch (NullPointerException e) {
                    // Invalid folder:
                    savesuccess = false;
                }
            }

            boolean sendsuccess = false;

            try {
                Transport.send(msg);
                Address sent[] = new Address[to.length + cc.length + bcc.length];
                int c1 = 0;
                int c2 = 0;
                for (c1 = 0; c1 < to.length; c1++) {
                    sent[c1] = to[c1];
                }
                for (c2 = 0; c2 < cc.length; c2++) {
                    sent[c1 + c2] = cc[c2];
                }
                for (int c3 = 0; c3 < bcc.length; c3++) {
                    sent[c1 + c2 + c3] = bcc[c3];
                }
                sendsuccess = true;
                throw new SendFailedException("success", new Exception("success"), sent, null, null);
            } catch (SendFailedException e) {
                session.handleTransportException(e);
            }

            //session.clearMessage();

            content = new XHTMLDocument(session.getModel(),
                    store.getStylesheet("sendresult.xsl", user.getPreferredLocale(), user.getTheme()));
            //              if(sendsuccess) session.clearWork();
        } catch (Exception e) {
            log.error("Could not send messsage", e);
            throw new DocumentNotFoundException("Could not send message. (Reason: " + e.getMessage() + ")");
        }

    } else if (head.isContentSet("ATTACH")) {
        /* Redirect request for attachment (unfortunately HTML forms are not flexible enough to
           have two targets without Javascript) */
        content = parent.getURLHandler().handleURL("/compose/attach", session, head);
    } else {
        throw new DocumentNotFoundException("Could not send message. (Reason: No content given)");
    }
    return content;
}

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

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

From source file:nl.nn.adapterframework.senders.MailSender.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection recipients, Collection attachments)
        throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }/*from w w w. j  a  v  a2s  .co m*/
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Element recipientElement = (Element) iter.next();
            String recipient = XmlUtils.getStringValue(recipientElement);
            if (StringUtils.isNotEmpty(recipient)) {
                String typeAttr = recipientElement.getAttribute("type");
                Message.RecipientType recipientType = Message.RecipientType.TO;
                if ("cc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.CC;
                }
                if ("bcc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.BCC;
                }
                msg.addRecipient(recipientType, new InternetAddress(recipient));
                recipientsFound = true;
                if (log.isDebugEnabled()) {
                    sb.append("[recipient(" + typeAttr + ")=" + recipient + "]");
                }
            } else {
                log.debug("empty recipient found, ignoring");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            iter = attachments.iterator();
            while (iter.hasNext()) {
                Element attachmentElement = (Element) iter.next();
                String attachmentText = XmlUtils.getStringValue(attachmentElement);
                String attachmentName = attachmentElement.getAttribute("name");
                String attachmentUrl = attachmentElement.getAttribute("url");
                String attachmentType = attachmentElement.getAttribute("type");
                String attachmentBase64 = attachmentElement.getAttribute("base64");
                if (StringUtils.isEmpty(attachmentType)) {
                    attachmentType = getDefaultAttachmentType();
                }
                if (StringUtils.isEmpty(attachmentName)) {
                    attachmentName = getDefaultAttachmentName();
                }
                log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url ["
                        + attachmentUrl + "]contents [" + attachmentText + "]");

                messageBodyPart = new MimeBodyPart();

                DataSource attachmentDataSource;
                if (!StringUtils.isEmpty(attachmentUrl)) {
                    attachmentDataSource = new URLDataSource(new URL(attachmentUrl));
                    messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource));
                }

                messageBodyPart.setFileName(attachmentName);

                if ("true".equalsIgnoreCase(attachmentBase64)) {
                    messageBodyPart.setDataHandler(decodeBase64(attachmentText));
                } else {
                    messageBodyPart.setText(attachmentText);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:nl.nn.adapterframework.senders.MailSenderOld.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection<Recipient> recipients,
        Collection<Attachment> attachments) throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }//  w w  w. j  ava2  s  .c o m
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Recipient recipient = (Recipient) iter.next();
            String value = recipient.value;
            String type = recipient.type;
            Message.RecipientType recipientType;
            if ("cc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.CC;
            } else if ("bcc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.BCC;
            } else {
                recipientType = Message.RecipientType.TO;
            }
            msg.addRecipient(recipientType, new InternetAddress(value));
            recipientsFound = true;
            if (log.isDebugEnabled()) {
                sb.append("[recipient [" + recipient + "]]");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            int counter = 0;
            iter = attachments.iterator();
            while (iter.hasNext()) {
                counter++;
                Attachment attachment = (Attachment) iter.next();
                Object value = attachment.getValue();
                String name = attachment.getName();
                if (StringUtils.isEmpty(name)) {
                    name = getDefaultAttachmentName() + counter;
                }
                log.debug("found attachment [" + attachment + "]");

                messageBodyPart = new MimeBodyPart();
                messageBodyPart.setFileName(name);

                if (value instanceof DataHandler) {
                    messageBodyPart.setDataHandler((DataHandler) value);
                } else {
                    messageBodyPart.setText((String) value);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:org.apache.axis.attachments.MimeUtils.java

/**
 * This routine will the multi part type and write it out to a stream.
 *
 * <p>Note that is does *NOT* pass <code>AxisProperties</code>
 * to <code>javax.mail.Session.getInstance</code>, but instead
 * the System properties.//from w ww  .j  a v  a 2s.  c  o m
 * </p>
 * @param os is the output stream to write to.
 * @param mp the multipart that needs to be written to the stream.
 */
public static void writeToMultiPartStream(java.io.OutputStream os, javax.mail.internet.MimeMultipart mp) {

    try {
        Properties props = AxisProperties.getProperties();

        props.setProperty("mail.smtp.host", "localhost"); // this is a bogus since we will never mail it.

        javax.mail.Session session = javax.mail.Session.getInstance(props, null);
        javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);

        message.setContent(mp);
        message.saveChanges();
        message.writeTo(os, filter);
    } catch (javax.mail.MessagingException e) {
        log.error(Messages.getMessage("javaxMailMessagingException00"), e);
    } catch (java.io.IOException e) {
        log.error(Messages.getMessage("javaIOException00"), e);
    }
}

From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java

/**
 * Create basic Message which contains all headers. No body is filled
 * /*from ww  w  .j  a va2  s. com*/
 * @param session the Session
 * @param action the action
 * @return message
 * @throws AddressException
 * @throws MessagingException
 * @throws ActionException
 */
protected Message createMessage(Session session, A action) throws AddressException, MessagingException {
    MimeMessage message = new MimeMessage(session);
    SMTPMessage m = action.getMessage();
    message.setFrom(new InternetAddress(m.getFrom()));

    userPreferences.addContact(m.getTo());
    userPreferences.addContact(m.getCc());
    userPreferences.addContact(m.getBcc());

    message.setRecipients(RecipientType.TO, MessageUtils.getRecipients(m.getTo()));
    message.setRecipients(RecipientType.CC, MessageUtils.getRecipients(m.getCc()));
    message.setRecipients(RecipientType.BCC, MessageUtils.getRecipients(m.getBcc()));
    message.setSubject(MessageUtils.encodeTexts(m.getSubject()));
    message.saveChanges();
    return message;
}

From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java

/**
 * Opens the IMAP folder, deletes all messages which match the magic subject and
 * creates a new message with an attachment which contains the object serialized
 *///from w  ww .j a v  a2s .  co m
protected static void saveUserPreferencesInIMAP(Log logger, User user, Session session, IMAPStore iStore,
        String folderName, String subject, Object object)
        throws MessagingException, IOException, InterruptedException {
    IMAPFolder folder = (IMAPFolder) iStore.getFolder(folderName);

    if (folder.exists() || folder.create(IMAPFolder.HOLDS_MESSAGES)) {
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }

        // Serialize the object
        ByteArrayOutputStream fout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(object);
        oos.close();
        ByteArrayInputStream is = new ByteArrayInputStream(fout.toByteArray());

        // Create a new message with an attachment which has the serialized object
        MimeMessage message = new MimeMessage(session);
        message.setSubject(subject);

        Multipart multipart = new MimeMultipart();
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent("This message contains configuration used by Hupa, do not delete it", "text/plain");
        multipart.addBodyPart(txtPart);
        FileItem item = createPreferencesFileItem(is, subject, HUPA_DATA_MIME_TYPE);
        multipart.addBodyPart(MessageUtils.fileitemToBodypart(item));
        message.setContent(multipart);
        message.saveChanges();

        // It seems it's not possible to modify the content of an existing message using the API
        // So I delete the previous message storing the preferences and I create a new one
        Message[] msgs = folder.getMessages();
        for (Message msg : msgs) {
            if (subject.equals(msg.getSubject())) {
                msg.setFlag(Flag.DELETED, true);
            }
        }

        // It is necessary to copy the message before saving it (the same problem in AbstractSendMessageHandler)
        message = new MimeMessage((MimeMessage) message);
        message.setFlag(Flag.SEEN, true);
        folder.appendMessages(new Message[] { message });
        folder.close(true);
        logger.info("Saved preferences " + subject + " in imap folder " + folderName + " for user " + user);
    } else {
        logger.error("Unable to save preferences " + subject + " in imap folder " + folderName + " for user "
                + user);
    }
}

From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java

/**
 * Create basic Message which contains all headers. No body is filled
 *
 * @param session the Session/*from w  w  w. j av a 2 s  .  c  o  m*/
 * @param action the action
 * @return message
 * @throws AddressException
 * @throws MessagingException
 */
public Message createMessage(Session session, SendMessageAction action)
        throws AddressException, MessagingException {
    MimeMessage message = new MimeMessage(session);
    SmtpMessage m = action.getMessage();
    message.setFrom(new InternetAddress(m.getFrom()));

    userPreferences.addContact(m.getTo());
    userPreferences.addContact(m.getCc());
    userPreferences.addContact(m.getBcc());

    message.setRecipients(RecipientType.TO, MessageUtils.getRecipients(m.getTo()));
    message.setRecipients(RecipientType.CC, MessageUtils.getRecipients(m.getCc()));
    message.setRecipients(RecipientType.BCC, MessageUtils.getRecipients(m.getBcc()));
    message.setSentDate(new Date());
    message.addHeader("User-Agent:", "HUPA, The Apache JAMES webmail client.");
    message.addHeader("X-Originating-IP", getClientIpAddr());
    message.setSubject(m.getSubject(), "utf-8");
    updateHeaders(message, action);
    message.saveChanges();
    return message;
}

From source file:org.apache.james.core.builder.MimeMessageBuilder.java

public MimeMessage build() throws MessagingException {
    Preconditions.checkState(!(text.isPresent() && content.isPresent()),
            "Can not get at the same time a text and a content");
    MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties()));
    if (text.isPresent()) {
        mimeMessage.setContent(text.get(), textContentType.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE));
    }/*from w ww  . j  av a  2 s.c o  m*/
    if (content.isPresent()) {
        mimeMessage.setContent(content.get());
    }
    if (sender.isPresent()) {
        mimeMessage.setSender(sender.get());
    }
    if (subject.isPresent()) {
        mimeMessage.setSubject(subject.get());
    }
    ImmutableList<InternetAddress> fromAddresses = from.build();
    if (!fromAddresses.isEmpty()) {
        mimeMessage.addFrom(fromAddresses.toArray(new InternetAddress[fromAddresses.size()]));
    }
    List<InternetAddress> toAddresses = to.build();
    if (!toAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[toAddresses.size()]));
    }
    List<InternetAddress> ccAddresses = cc.build();
    if (!ccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.CC,
                ccAddresses.toArray(new InternetAddress[ccAddresses.size()]));
    }
    List<InternetAddress> bccAddresses = bcc.build();
    if (!bccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.BCC,
                bccAddresses.toArray(new InternetAddress[bccAddresses.size()]));
    }

    MimeMessage wrappedMessage = MimeMessageWrapper.wrap(mimeMessage);

    List<Header> headerList = headers.build();
    for (Header header : headerList) {
        if (header.name.equals("Message-ID") || header.name.equals("Date")) {
            wrappedMessage.setHeader(header.name, header.value);
        } else {
            wrappedMessage.addHeader(header.name, header.value);
        }
    }
    wrappedMessage.saveChanges();

    return wrappedMessage;
}