用javamail创建带图片的邮件

首先导入两个架包:

mail.jar

activation.jar

 

代码如下:

package cn.test.demo;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class ImageMail {

	/**
	 * 
	 * 创建带图片的邮件
	 * @throws MessagingException 
	 * @throws AddressException 
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public static void main(String[] args) throws AddressException, MessagingException, FileNotFoundException, IOException {

		
		//1.创建邮件
		Session session = Session.getInstance(new Properties());  //创建空的session
		MimeMessage message = new MimeMessage(session);
		
		//2.设置邮件的基本信息
		message.setFrom(new InternetAddress("[email protected]"));  //发件人
		message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); //收件人
		message.setSubject("test");  //邮件的主题
		
		//3.设置邮件正文
		MimeBodyPart text = new MimeBodyPart();
		text.setContent("xxxxxxx<br/><img src='cid:xx.jpg'><br/>xxxxx<br/><img src='cid:yy.jpg'><br/>xxxxxx", "text/html");
		
		//4.设置邮件图片1
		MimeBodyPart image = new MimeBodyPart();
		image.setDataHandler(new DataHandler(new FileDataSource("src\\1.jpg")));  //javamail jaf
		image.setContentID("xx.jpg");
		
		//4.设置邮件图片1
		MimeBodyPart image1 = new MimeBodyPart();
		image1.setDataHandler(new DataHandler(new FileDataSource("src\\2.jpg")));  //javamail jaf
		image1.setContentID("yy.jpg");
		
		//5.描述数据关系
		MimeMultipart mm = new MimeMultipart();
		mm.addBodyPart(text);
		mm.addBodyPart(image);
		mm.addBodyPart(image1);
		mm.setSubType("related");

		message.setContent(mm);
		message.saveChanges(); //保存更新
		
		message.writeTo(new FileOutputStream("c:\\1.eml"));
		
	}

}


 

你可能感兴趣的:(image,session,properties,String,Class,javamail)