001    /**
002     * Copyright (c) 2000-2010 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.FileUtil;
018    import com.liferay.portal.kernel.util.StringBundler;
019    import com.liferay.portal.kernel.util.StringPool;
020    
021    import java.io.IOException;
022    import java.io.InputStream;
023    
024    import javax.mail.Address;
025    import javax.mail.MessagingException;
026    import javax.mail.Part;
027    import javax.mail.internet.InternetAddress;
028    
029    /**
030     * @author Brian Wing Shun Chan
031     */
032    public class JavaMailUtil {
033    
034            public static byte[] getBytes(Part part)
035                    throws IOException, MessagingException {
036    
037                    InputStream is = part.getInputStream();
038    
039                    try {
040                            return FileUtil.getBytes(is);
041                    }
042                    finally {
043                            is.close();
044                    }
045            }
046    
047            public static String toUnicodeString(Address[] addresses) {
048                    return toUnicodeString((InternetAddress[])addresses);
049            }
050    
051            public static String toUnicodeString(InternetAddress[] addresses) {
052                    if ((addresses == null) || (addresses.length == 0)) {
053                            return StringPool.BLANK;
054                    }
055    
056                    StringBundler sb = new StringBundler(addresses.length * 2 - 1);
057    
058                    for (int i = 0; i < addresses.length; i++) {
059                            if (addresses[i] != null) {
060                                    sb.append(addresses[i].toUnicodeString());
061                            }
062    
063                            if ((i + 1) != addresses.length) {
064                                    sb.append(", ");
065                            }
066                    }
067    
068                    return sb.toString();
069            }
070    
071    }