javaMail邮件发送模版(实现图片、附件的添加)

package com.cn.javamail;


import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;


import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;


public class Demo3 {


/**
* @param args
*/
public static void main(String[] args) throws Exception {
// 定义一个对象props,用于设置服务环境信息
Properties props = new Properties();
// Session类用于定义整个应用程序所需的环境信息
Session session = Session.getInstance(props);

   session.setDebug(true);

// 定义一份邮件
MimeMessage mmsg = new MimeMessage(session);
mmsg.setSubject("你们的Java培训真的是最牛的吗?");
MimeMultipart msgMultipart = new MimeMultipart("mixed");
mmsg.setContent(msgMultipart);


MimeBodyPart attach1 = new MimeBodyPart();
MimeBodyPart attach2 = new MimeBodyPart();
MimeBodyPart contents = new MimeBodyPart();
msgMultipart.addBodyPart(attach1);
msgMultipart.addBodyPart(attach2);
msgMultipart.addBodyPart(contents);
// ********第一个附件********

// 定义一个数据源对象
DataSource ds1 = new FileDataSource("F:\\file\\test1.doc");
// 定义一个DataHandler用来,包装一文件
DataHandler dh1 = new DataHandler(ds1);
attach1.setDataHandler(dh1);
//设置附件的名称以及解决中文字符编码问题
attach1.setFileName(MimeUtility.encodeText("测试1.doc"));



// *********第二个附件*****************


// 定义一个数据源对象
DataSource ds2 = new FileDataSource("F:\\file\\test2.doc");
// 定义一个DataHandler用来,包装一文件
DataHandler dh2 = new DataHandler(ds2);
attach2.setDataHandler(dh2);
attach2.setFileName(MimeUtility.encodeText("测试2.doc"));





// 正文(复杂体)
MimeMultipart bodyMultipart = new MimeMultipart("related");
contents.setContent(bodyMultipart);

MimeBodyPart htmlPart = new MimeBodyPart();
MimeBodyPart imagePart = new MimeBodyPart();
bodyMultipart.addBodyPart(htmlPart);
bodyMultipart.addBodyPart(imagePart);


DataSource ds3 = new FileDataSource("F:\\file\\image.jpg");
DataHandler dh3 = new DataHandler(ds3);
imagePart.setDataHandler(dh3);
   imagePart.setHeader("Content-Location", "http://www.pengtian.cn/image.jpg");


htmlPart.setContent(
"<font style='color:red;font-size:40px;'>4645645454555</font><img src='http://www.pengtian.cn/image.jpg'>",
"text/html;charset=utf-8");


// 根据对象去生成一份邮件
mmsg.saveChanges();
// 定义一个输出流对象
OutputStream os = new FileOutputStream("F:\\file\\denmo4.eml");
mmsg.writeTo(os);
// 关闭输出流对象
os.close();
}


}

你可能感兴趣的:(exception,session,properties,测试,File,javamail)