All Downloads are FREE. Search and download functionalities are using the official Maven repository.

top.coos.extra.mail.InternalMailUtil Maven / Gradle / Ivy

There is a newer version: 2.2.7.1
Show newest version
package top.coos.extra.mail;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;

import top.coos.util.ArrayUtil;

/**
 * 邮件内部工具类

 * @since 3.2.3
 */
public class InternalMailUtil {
	
	/**
	 * 将多个字符串邮件地址转为{@link InternetAddress}列表
* 单个字符串地址可以是多个地址合并的字符串 * * @param addrStrs 地址数组 * @param charset 编码(主要用于中文用户名的编码) * @return 地址数组 * @since 4.0.3 */ public static InternetAddress[] parseAddressFromStrs(String[] addrStrs, Charset charset) { final List resultList = new ArrayList<>(addrStrs.length); InternetAddress[] addrs; for (int i = 0; i < addrStrs.length; i++) { addrs = parseAddress(addrStrs[i], charset); if(ArrayUtil.isNotEmpty(addrs)) { for(int j = 0 ; j < addrs.length; j++) { resultList.add(addrs[j]); } } } return resultList.toArray(new InternetAddress[resultList.size()]); } /** * 解析第一个地址 * * @param address 地址字符串 * @param charset 编码 * @return 地址列表 */ public static InternetAddress parseFirstAddress(String address, Charset charset) { final InternetAddress[] internetAddresses = parseAddress(address, charset); if (ArrayUtil.isEmpty(internetAddresses)) { try { return new InternetAddress(address); } catch (AddressException e) { throw new MailException(e); } } return internetAddresses[0]; } /** * 将一个地址字符串解析为多个地址
* 地址间使用" "、","、";"分隔 * * @param address 地址字符串 * @param charset 编码 * @return 地址列表 */ public static InternetAddress[] parseAddress(String address, Charset charset) { InternetAddress[] addresses; try { addresses = InternetAddress.parse(address); } catch (AddressException e) { throw new MailException(e); } //编码用户名 if (ArrayUtil.isNotEmpty(addresses)) { for (InternetAddress internetAddress : addresses) { try { internetAddress.setPersonal(internetAddress.getPersonal(), charset.name()); } catch (UnsupportedEncodingException e) { throw new MailException(e); } } } return addresses; } /** * 编码中文字符
* 编码失败返回原字符串 * * @param text 被编码的文本 * @param charset 编码 * @return 编码后的结果 */ public static String encodeText(String text, Charset charset) { try { return MimeUtility.encodeText(text, charset.name(), null); } catch (UnsupportedEncodingException e) { // ignore } return text; } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy