邮件的基本信息类
MailInfo.javapublic class MailInfo {
// 发送邮件的服务器的IP和端口
private String mailServerHost;
private String mailServerPort = "25";
// 邮件发送者的地址
private String fromAddress;
// 邮件接收者的地址
private String toAddress;
// 登陆邮件发送服务器的用户名和密码
private String userName;
private String password;
// 是否需要身份验证
private boolean validate = false;
// 邮件主题
private String subject;
// 邮件的文本内容
private String content;
// 邮件附件的文件名
private String[] attachFileNames;
发送邮件Service
SpringMailService.javapublic class SpringMailService { private JavaMailSender sender1; // 发送Marltipart文件,包含附件
public void sendMarltipartMail(MailInfo info)
throws  Exception{
MimeMessage msg = sender1.createMimeMessage();
// true表示非arltipart,UTF-8为字符编码
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
helper.setSubject(info.getSubject());
helper.setFrom(info.getFromAddress());
helper.setTo(info.getToAddress());
String[] files = info.getAttachFileNames();//附件
if (files != null && files.length > 0) {
for (String fileName : files) {
//获取资源文件
ClassPathResource  file  = new ClassPathResource(fileName);
helper.addAttachment(file.getFilename(), file.getFile());//设置附件的名称及其文件流
}
}
sender1.send(msg);
} public void setSender(JavaMailSender sender) {
this.sender1 = sender;
}测试类public class MailTest { public static void main(String[] args) throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
SpringMailService sss = (SpringMailService) ctx
.getBean("springMailService");
MailInfo mailInfo = new MailInfo();
// 这个类主要是设置邮件 mailInfo.setMailServerHost("smtp.163.com");//服务器地址
mailInfo.setMailServerPort("25");//端口
mailInfo.setValidate(true); //是否验证,这个地方是必须的
mailInfo.setFromAddress("[email protected]");//这个是你的邮箱 ,在程序发送一方需对应,就是你在配置文件的发送邮箱的名称
mailInfo.setToAddress("[email protected]");//目的地

String[] fileNames = new String[]{"QQ.png"};
mailInfo.setAttachFileNames(fileNames);
mailInfo.setSubject("这带有附件的邮件");
sss.sendMarltipartMail(mailInfo);//发送带附件的文件
System.out.println("发送带附件的邮件,发送完毕"); }}
运行报了错
javax.mail.MessagingExceptionIOException while sending message;
  nested exception is:
java.io.IOException: javax.mail.MessagingException: Empty multipart: multipart/related; 
boundary="----=_Part_3_1882017.1300088905008"