在發送帶有附件的郵件中,遇到了附件中文名亂碼的問題,現已解決。只談解決方法,具體原理解析請參考文章底部連接。html
主要遇到的問題有兩個:java
解決方案:apache
1.解決第一個的問題是用MimeUtility.encodeText()進行解碼this
attach.setName(MimeUtility.encodeText(f.getName()));
2.解決第二個問題設置了一個系統屬性(該屬性最好是在聲明對象前設置,否則有可能無效的).net
System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
代碼示例:code
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.mail.EmailAttachment; import org.apache.commons.mail.HtmlEmail; import javax.mail.internet.MimeUtility; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Class <code>Object</code> is the root of the class hierarchy. * Every class has <code>Object</code> as a superclass. All objects, * including arrays, implement the methods of this class. * * @author Administrator * @version 1.0 * @see * @since JDK1.7 * <p> * History * Created by Administrator on 2018/2/2 0002. */ public class MailTest { public static void main(String[] args) throws IOException { System.getProperties().setProperty("mail.mime.splitlongparameters", "false"); HtmlEmail email = new HtmlEmail(); email.setHostName("郵箱主機"); email.setAuthentication("發送者郵箱","密碼"); email.setCharset("UTF-8"); try { String[] receivers = new String[]{"接收者郵箱1","接收者郵箱2"}; for (String receiver : receivers) { email.addTo(receiver.trim()); } email.setFrom("發送者郵箱","234234324234"); email.setSubject("test"); email.setMsg("<html><div style=\"background:red;\">尼瑪嗨</div></html>"); List<String> list = new ArrayList<String>(); list.add("C:\\Users\\Administrator\\Downloads\\1111_滴滴出行發單是對方水在發送附件水電費水電費水電費水電費是的防守打法水電費水電費水電費水電費是的防守打法水電費水電費水電費水電費是的在發送附件水電費水電費水電費水電費是的防守打法水電費水電費水電費水電費是的防守打法水電費水電費水電費水電費是的電費水電費sdfsdfs是的s.pdf"); if (!CollectionUtils.isEmpty(list)) { for (String attachment : list) { EmailAttachment attach = new EmailAttachment(); File f = new File(attachment); attach.setName(f.getName()); attach.setURL(new URL("附件連接")); email.attach(attach); } } String result = email.send(); }catch (Exception e){ e.printStackTrace(); } } }
參考連接:htm
http://blog.csdn.net/wty19/article/details/50607411對象
http://blog.csdn.net/albert0707/article/details/69284700blog