List of usage examples for javax.mail.internet MimeUtility encode
public static OutputStream encode(OutputStream os, String encoding) throws MessagingException
From source file:com.stimulus.archiva.store.MessageStore.java
public void writeTo(MimePart part, OutputStream os, String[] includeList) throws IOException, MessagingException { LineOutputStream los = null;//from ww w. j a v a 2s . c o m if (os instanceof LineOutputStream) { los = (LineOutputStream) os; } else { los = new LineOutputStream(os); } Enumeration hdrLines = part.getMatchingHeaderLines(includeList); while (hdrLines.hasMoreElements()) { String line = (String) hdrLines.nextElement(); los.writeln(line); } los.writeln(); os = MimeUtility.encode(os, part.getEncoding()); part.getDataHandler().writeTo(os); os.flush(); }
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 w w .j a v a2 s. c o m*/ 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:org.agnitas.beans.impl.MailingComponentImpl.java
public String makeEMMBlock() { ByteArrayOutputStream baos = null; if (type == TYPE_TEMPLATE) { try {//w w w.java 2 s . com return new String(binaryBlock, "UTF8"); } catch (Exception e) { logger.error("makeEMMBlock: encoding error", e); return " "; } } else { try { baos = new ByteArrayOutputStream(); OutputStream dos = MimeUtility.encode(new DataOutputStream(baos), "base64"); dos.write(binaryBlock); dos.flush(); return baos.toString(); } catch (Exception e) { return null; } } }
From source file:org.apache.james.core.MimeMessageUtil.java
/** * Write message body of given mimeessage to the given outputStream * //from w w w . j a va 2s.co m * @param message * the MimeMessage used as input * @param bodyOs * the OutputStream to write the message body to * @throws IOException * @throws UnsupportedDataTypeException * @throws MessagingException */ public static void writeMessageBodyTo(MimeMessage message, OutputStream bodyOs) throws IOException, MessagingException { OutputStream bos; InputStream bis; try { // Get the message as a stream. This will encode // objects as necessary, and we have some input from // decoding an re-encoding the stream. I'd prefer the // raw stream, but see bos = MimeUtility.encode(bodyOs, message.getEncoding()); bis = message.getInputStream(); } catch (UnsupportedDataTypeException udte) { /* * If we get an UnsupportedDataTypeException try using the raw input * stream as a "best attempt" at rendering a message. * * WARNING: JavaMail v1.3 getRawInputStream() returns INVALID * (unchanged) content for a changed message. getInputStream() works * properly, but in this case has failed due to a missing * DataHandler. * * MimeMessage.getRawInputStream() may throw a "no content" * MessagingException. In JavaMail v1.3, when you initially create a * message using MimeMessage APIs, there is no raw content * available. getInputStream() works, but getRawInputStream() throws * an exception. If we catch that exception, throw the UDTE. It * should mean that someone has locally constructed a message part * for which JavaMail doesn't have a DataHandler. */ try { bis = message.getRawInputStream(); bos = bodyOs; } catch (javax.mail.MessagingException _) { throw udte; } } catch (javax.mail.MessagingException me) { /* * This could be another kind of MessagingException thrown by * MimeMessage.getInputStream(), such as a * javax.mail.internet.ParseException. * * The ParseException is precisely one of the reasons why the * getRawInputStream() method exists, so that we can continue to * stream the content, even if we cannot handle it. Again, if we get * an exception, we throw the one that caused us to call * getRawInputStream(). */ try { bis = message.getRawInputStream(); bos = bodyOs; } catch (javax.mail.MessagingException _) { throw me; } } try { IOUtils.copy(bis, bos); } finally { IOUtils.closeQuietly(bis); } }
From source file:org.apache.james.server.core.MimeMessageUtil.java
/** * Write message body of given mimeessage to the given outputStream * /*w w w. jav a 2 s .c o m*/ * @param message * the MimeMessage used as input * @param bodyOs * the OutputStream to write the message body to * @throws IOException * @throws UnsupportedDataTypeException * @throws MessagingException */ public static void writeMessageBodyTo(MimeMessage message, OutputStream bodyOs) throws IOException, MessagingException { OutputStream bos; InputStream bis; try { // Get the message as a stream. This will encode // objects as necessary, and we have some input from // decoding an re-encoding the stream. I'd prefer the // raw stream, but see bos = MimeUtility.encode(bodyOs, message.getEncoding()); bis = message.getInputStream(); } catch (UnsupportedDataTypeException | MessagingException udte) { /* * If we get an UnsupportedDataTypeException try using the raw input * stream as a "best attempt" at rendering a message. * * WARNING: JavaMail v1.3 getRawInputStream() returns INVALID * (unchanged) content for a changed message. getInputStream() works * properly, but in this case has failed due to a missing * DataHandler. * * MimeMessage.getRawInputStream() may throw a "no content" * MessagingException. In JavaMail v1.3, when you initially create a * message using MimeMessage APIs, there is no raw content * available. getInputStream() works, but getRawInputStream() throws * an exception. If we catch that exception, throw the UDTE. It * should mean that someone has locally constructed a message part * for which JavaMail doesn't have a DataHandler. */ try { bis = message.getRawInputStream(); bos = bodyOs; } catch (javax.mail.MessagingException ignored) { throw udte; } } try (InputStream input = bis) { IOUtils.copy(input, bos); } }
From source file:org.sakaiproject.user.impl.OneWayHash.java
/** * Encode the clear text into an encoded form. * /* w w w. jav a2 s . c o m*/ * @param clear * The text to encode. * @param truncated * return a value truncated as we used to be before fixing SAK-5922 (works only with MD5 algorithm base64'ed) * @return The encoded and base64'ed text. */ public static String encode(String clear, boolean truncated) { try { // compute the digest using the MD5 algorithm MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digest = md.digest(clear.getBytes("UTF-8")); // encode as base64 ByteArrayOutputStream bas = new ByteArrayOutputStream(digest.length + digest.length / 3 + 1); OutputStream encodedStream = MimeUtility.encode(bas, "base64"); encodedStream.write(digest); // we used to pick up the encoding before it was complete, leaving off the last 4 characters of the encoded value String truncatedValue = bas.toString(); // close the stream to complete the encoding encodedStream.close(); String rv = bas.toString(); // if we are asking for the truncated value, return that if (truncated) return truncatedValue; return rv; } catch (Exception e) { M_log.warn("OneWayHash.encode: exception: " + e); return null; } }
From source file:org.sakaiproject.user.impl.PasswordService.java
/** * Digest and Base64 encode the password. * @param password The password to hash. * @param algorithm The Digest Algorithm to use. * @return The digested password or <code>null</code> if it failed. *//* www. j a v a 2s .c o m*/ protected String hash(String password, String algorithm) { try { // compute the digest using the MD5 algorithm MessageDigest md = MessageDigest.getInstance(algorithm); byte[] digest = md.digest(password.getBytes("UTF-8")); // encode as base64 ByteArrayOutputStream bas = new ByteArrayOutputStream(lengthBase64(digest.length)); OutputStream encodedStream = MimeUtility.encode(bas, "base64"); encodedStream.write(digest); // close the stream to complete the encoding encodedStream.close(); String rv = bas.toString().trim(); // '\r\n' is appended by encode() return rv; } catch (Exception e) { log.warn("Failed with " + algorithm, e); return null; } }
From source file:org.sakaiproject.user.impl.PasswordService.java
/** * Generate a salt which is Base64 encoded. * @param length The number of bytes to use for the source. * @return A Base64 version of the salt. So it's longer than the source length. *///from ww w .j a v a 2 s . co m protected String salt(int length) { try { byte[] salt = new byte[length]; saltSource.nextBytes(salt); ByteArrayOutputStream bas = new ByteArrayOutputStream(lengthBase64(length)); OutputStream saltStream; saltStream = MimeUtility.encode(bas, "base64"); saltStream.write(salt); saltStream.close(); String rv = bas.toString().trim(); // '\r\n' is appended by encode() return rv; } catch (Exception e) { log.warn("Failed to generate salt.", e); } return ""; }