import java.io.UnsupportedEncodingException; import javax.mail.internet.MimeUtility; import org.apache.commons.mail.EmailAttachment; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.MultiPartEmail; public class MailTest { public static void sendMultiPartEmail() throws EmailException { EmailAttachment attachment = new EmailAttachment(); // 设置附件路径 attachment.setPath("C:/test.log"); attachment.setDisposition(EmailAttachment.ATTACHMENT); // 附件描述 attachment.setDescription("This is Smile picture"); String fileName = "中文名附件.log"; try { fileName = MimeUtility.encodeText(fileName); // 解决中文附件乱码 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } attachment.setName(fileName); // 创建一个含附件的email MultiPartEmail multipartemail = new MultiPartEmail(); multipartemail.setHostName("smtp.qq.com");// 设置主机名称 multipartemail.setCharset("GBK");// 设置字符编码 multipartemail.addTo("您的QQ号@qq.com"); // 设置发送邮件目的地址 // 设置发送源地址和显示名,此处是自己发给自己,可以填任意邮件地址 multipartemail.setFrom("您的QQ号@qq.com", "邮件里显示的中文名"); multipartemail.setAuthentication("您的QQ号,不含@qq.com", "您的QQ密码");// 设置用户名和密码 multipartemail.setSubject("测试发送附件");// 设置主题 multipartemail.setMsg("暂无");// 设置邮件内容 multipartemail.attach(attachment);// 添加附件 multipartemail.send();// 发送邮件 } public static void main(String[] args) { try { MailTest.sendMultiPartEmail(); } catch (EmailException e) { e.printStackTrace(); } System.out.println("send over"); } }
原来需要用MimeUtility.encodeText(fileNameString)转一下就可以不乱码了,记一下。
下附完整发送含附件的邮件。
原文地址:https://www.cnblogs.com/bevis-byf/p/11760778.html
时间: 2024-10-12 03:53:02