/*** 3. 带图片资源以及附件的邮件
*@author**/
public classApp_3ImgAndAtta {//初始化参数
private staticProperties prop;//发件人
private static InternetAddress sendMan = null;static{
prop= newProperties();
prop.put("mail.transport.protocol", "smtp"); //指定协议
prop.put("mail.smtp.host", "localhost"); //主机 stmp.qq.com
prop.put("mail.smtp.port", 25); //端口
prop.put("mail.smtp.auth", "true"); //用户密码认证
prop.put("mail.debug", "true"); //调试模式
try{
sendMan= new InternetAddress("zhangsan@123.com");
}catch(AddressException e) {throw newRuntimeException(e);
}
}
@Testpublic void testSend() throwsException {//1. 创建邮件会话
Session session =Session.getDefaultInstance(prop);//2. 创建邮件对象
MimeMessage message = newMimeMessage(session);//3. 设置参数:标题、发件人、收件人、发送时间、内容
message.setSubject("带图片邮件");
message.setSender(sendMan);
message.setRecipient(RecipientType.TO,new InternetAddress("lisi@123.com"));
message.setSentDate(newDate());/** 带附件(图片)邮件开发*/
//构建一个总的邮件块
MimeMultipart mixed = new MimeMultipart("mixed");//---> 总邮件快,设置到邮件对象中
message.setContent(mixed);//左侧: (文本+图片资源)
MimeBodyPart left = newMimeBodyPart();//右侧: 附件
MimeBodyPart right = newMimeBodyPart();//设置到总邮件块
mixed.addBodyPart(left);
mixed.addBodyPart(right);/******附件********/String attr_path= this.getClass().getResource("a.docx").getPath();
DataSource attr_ds= new FileDataSource(newFile(attr_path));
DataHandler attr_handler= newDataHandler(attr_ds);
right.setDataHandler(attr_handler);
right.setFileName("a.docx");/***************设置邮件内容: 多功能用户邮件 (related)*******************/
//4.1 构建一个多功能邮件块
MimeMultipart related = new MimeMultipart("related");//----> 设置到总邮件快的左侧中
left.setContent(related);//4.2 构建多功能邮件块内容 = 左侧文本 + 右侧图片资源
MimeBodyPart content = newMimeBodyPart();
MimeBodyPart resource= newMimeBodyPart();//设置具体内容: a.资源(图片)
String filePath = App_3ImgAndAtta.class.getResource("8.jpg").getPath();
DataSource ds= new FileDataSource(newFile(filePath));
DataHandler handler= newDataHandler(ds);
resource.setDataHandler(handler);
resource.setContentID("8.jpg"); //设置资源名称,给外键引用//设置具体内容: b.文本
content.setContent(" 好哈哈!", "text/html;charset=UTF-8");
related.addBodyPart(content);
related.addBodyPart(resource);//5. 发送
Transport trans =session.getTransport();
trans.connect("zhangsan", "888");
trans.sendMessage(message, message.getAllRecipients());
trans.close();
}
}