Java Encode encodeEmail(String s)

Here you can find the source of encodeEmail(String s)

Description

Encode non ascii characters present in emails like: =?ISO-8859-1?Q?No=20hay=20ma=F1ana?=

License

Apache License

Declaration

public static String encodeEmail(String s) 

Method Source Code

//package com.java2s;
/****************************************************************
 * Licensed to the Apache Software Foundation (ASF) under one   *
 * or more contributor license agreements.  See the NOTICE file *
 * distributed with this work for additional information        *
 * regarding copyright ownership.  The ASF licenses this file   *
 * to you under the Apache License, Version 2.0 (the            *
 * "License"); you may not use this file except in compliance   *
 * with the License.  You may obtain a copy of the License at   *
 *                                                              *
 *   http://www.apache.org/licenses/LICENSE-2.0                 *
 *                                                              *
 * Unless required by applicable law or agreed to in writing,   *
 * software distributed under the License is distributed on an  *
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
 * KIND, either express or implied.  See the License for the    *
 * specific language governing permissions and limitations      *
 * under the License.                                           *
 ****************************************************************/

import java.io.UnsupportedEncodingException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.internet.MimeUtility;

public class Main {
    /**// w  w  w. j  a  v  a 2 s.  co  m
     * Encode non ascii characters present in emails like:
     *
     * =?ISO-8859-1?Q?No=20hay=20ma=F1ana?= <hello@hupa.org>
     */
    public static String encodeEmail(String s) {
        if (s == null) {
            return s;
        }
        Pattern p = Pattern.compile("^\\s*(.*?)\\s*(<[^>]+>)\\s*");
        Matcher m = p.matcher(s);
        return m.matches() ? encodeTexts(m.group(1)) + " " + m.group(2) : s;
    }

    /**
     * Encode non ascii characters present in email headers
     */
    public static String encodeTexts(String s) {
        String ret = s;
        if (s != null) {
            try {
                ret = MimeUtility.encodeText(s, "ISO-8859-1", null);
            } catch (UnsupportedEncodingException e) {
            }
        }
        return ret;
    }
}

Related

  1. encodeAttribute(String value)
  2. encodeBackslashAhead(char c, char next, Appendable buffer)
  3. encodeCodePoolData(InputStream input)
  4. encodedInputStreamReader(InputStream stream, String encoding)
  5. encodedStringToProperties(String theEncodedPropertyString)
  6. encodeFile(String filePath)
  7. encodeForFilter(final String filterString)
  8. encodeForString(String str)
  9. encodeGoomojiSubject(String subject)