javamail 文本和多媒体混合

在邮件内容中既包含文本内容页包含“多媒体”文件,混排的情况(related)

package hb.test;

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

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
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;

public class MainBodyTest {

	public static void main(String[] args) throws Exception{

		Properties props = new Properties();
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.transport.protocol", "smtp");
		
		Session session = Session.getInstance(props);
		session.setDebug(true);
		
		Message msg = new MimeMessage(session);
		msg.setText("来自hbiao68@@yeah.net 的 邮件测试");
		msg.setSubject("测试邮件");
		msg.setFrom(new InternetAddress("[email protected]"));
		msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]") );
		
		msg.setSentDate(new Date());
		//表示邮件中的内容是“多媒体”格式——既有文本也有附件
		MimeMultipart msgMultipart = new MimeMultipart("mixed");
		msg.setContent(msgMultipart);
		
		MimeBodyPart content = new MimeBodyPart();
		msgMultipart.addBodyPart(content);
		//下面的内容是显示在“正文中的”,即文字内容中添加多媒体文件
		MimeMultipart bodyMultipart = new MimeMultipart("related");
		content.setContent(bodyMultipart);
		MimeBodyPart htmlPart = new MimeBodyPart();
		MimeBodyPart gifPart = new MimeBodyPart();
		bodyMultipart.addBodyPart(htmlPart);
		bodyMultipart.addBodyPart(gifPart);
		
		DataSource gifds = new FileDataSource("c:\\d.jpg");
		DataHandler gifdh = new DataHandler(gifds);
		gifPart.setDataHandler(gifdh);
		gifPart.setContentID("dfasdsaf");
		//说明这种多媒体的名称标记为"huangbiao.gif"
//			gifPart.setHeader("Content-Location", "http://www.itcast.cn/logo.gif");
		gifPart.setHeader("Content-Location", "huangbiao.gif");
		//引用上面添加的多媒体,即"huangbiao.gif"
//			htmlPart.setContent("图片如图<img src='http://www.itcast.cn/logo.gif'>"
//					, "text/html;charset=gbk");
		htmlPart.setContent("图片如图<img src='huangbiao.gif'>"
				, "text/html;charset=gbk");
		//发送邮件
//		Transport transport = session.getTransport();
//		transport.connect("smtp.yeah.net", 25, "用户名", "密码");
//		transport.sendMessage(msg, new Address[]{new InternetAddress("[email protected]")});
//
//		transport.close();
		
		msg.saveChanges();
		//保存邮件
		OutputStream ips = new FileOutputStream("c:\\demo3.eml");
		msg.writeTo(ips);
		ips.close();
	}

}

备注:上面的代码可以保存邮件,然后在打开保存的邮件是显示正常的(文本内容中含有多媒体文件)

但是,如果发送邮件却会提示失败,不是因为代码写错了,而是因为我们使用的邮件系统是否支持这种related方式

猜你喜欢

转载自hbiao68.iteye.com/blog/1611650