001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.util.mail;
016    
017    import com.liferay.portal.kernel.util.ArrayUtil;
018    import com.liferay.portal.kernel.util.FileUtil;
019    import com.liferay.portal.kernel.util.StringBundler;
020    import com.liferay.portal.kernel.util.StringPool;
021    
022    import java.io.IOException;
023    import java.io.InputStream;
024    
025    import javax.mail.Address;
026    import javax.mail.MessagingException;
027    import javax.mail.Part;
028    import javax.mail.internet.InternetAddress;
029    
030    /**
031     * @author Brian Wing Shun Chan
032     */
033    public class JavaMailUtil {
034    
035            public static byte[] getBytes(Part part)
036                    throws IOException, MessagingException {
037    
038                    InputStream is = part.getInputStream();
039    
040                    return FileUtil.getBytes(is);
041            }
042    
043            public static String toUnicodeString(Address[] addresses) {
044                    return toUnicodeString((InternetAddress[])addresses);
045            }
046    
047            public static String toUnicodeString(InternetAddress[] addresses) {
048                    if (ArrayUtil.isEmpty(addresses)) {
049                            return StringPool.BLANK;
050                    }
051    
052                    StringBundler sb = new StringBundler(addresses.length * 2 - 1);
053    
054                    for (int i = 0; i < addresses.length; i++) {
055                            if (addresses[i] != null) {
056                                    sb.append(addresses[i].toUnicodeString());
057                            }
058    
059                            if ((i + 1) != addresses.length) {
060                                    sb.append(", ");
061                            }
062                    }
063    
064                    return sb.toString();
065            }
066    
067    }