JavaMail邮件发送-发送带附件的邮件

之前已经看到,如果消息包指定了他们之间的关系,增加一个文件进去,邮箱就会显示成普通附件

但是那毕竟不是附件,附件就是附件不能含糊

 

其实增加附件很简单

指定消息包内元素为混合关系

增加附件并指定附件的名称

 

代码如下:

package com.mail;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
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 Html_File_InnerFile {
	public static void main(String[] args) throws Exception {
		Properties props = new Properties();
		props.put( "mail.smtp.host ", "smtp.163.com ");
		props.put("mail.smtp.auth", "true");
		Session session = Session.getInstance(props);
		Message message = new MimeMessage(session);
		InternetAddress from = new InternetAddress("[email protected]");
		from.setPersonal(MimeUtility.encodeText("风中落叶"));
		message.setFrom(from);
		InternetAddress to = new InternetAddress("[email protected]");
		message.setRecipient(Message.RecipientType.TO, to);
		message.setSubject(MimeUtility.encodeText("强哥邀请,谁敢不从!"));
		message.setSentDate(new Date());
		MimeMultipart msgMultipart = new MimeMultipart("mixed");// 指定为混合关系
		message.setContent(msgMultipart);
		// 邮件内容
		MimeBodyPart htmlPart = new MimeBodyPart();
		htmlPart.setContent(
						""
								+ "
" + "这是测试邮件,请勿回复" + "
", "text/html;charset=UTF-8"); // TODO 组装的顺序非常重要,一定要先组装文本域,再组装文件 msgMultipart.addBodyPart(htmlPart); // 组装附件 MimeBodyPart file = new MimeBodyPart(); FileDataSource file_datasource = new FileDataSource("D:\\img201008031058340.zip"); DataHandler dh = new DataHandler(file_datasource); file.setDataHandler(dh); // 附件区别内嵌内容的一个特点是有文件名,为防止中文乱码要编码 file.setFileName(MimeUtility.encodeText(dh.getName())); msgMultipart.addBodyPart(file); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect("smtp.163.com", 25, "test20120711120200", "test123456"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); System.out.println("发送完毕"); } }

  

主要组装元素的时候一定要先组装邮件内容再组装附件

 无论在 客户端工具还是邮箱,都是提示附件,邮件还是带背景图片的

 

JavaMail邮件发送-发送带附件的邮件_第1张图片

 

 

 附件名称是你自己指定的

 

请您到ITEYE看我的原创:http://cuisuqiang.iteye.com

或支持我的个人博客,地址:http://www.javacui.com

 

你可能感兴趣的:(J2EE)