javamail添加附件

 

 给邮件添加附件

 

 

package hb.test;

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.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class FujianTest {

	public static void main(String[] args) {
		
		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);
		try {
			msg.setText("来自hbiao68@@yeah.net 的 邮件测试");
			msg.setSubject("测试邮件");
			msg.setFrom(new InternetAddress("[email protected]"));
			
			msg.setSentDate(new Date());
			//添加附件必须设置邮件类型
			MimeMultipart msgMultipart = new MimeMultipart("mixed");
			msg.setContent(msgMultipart);
			
			MimeBodyPart attch1 = new MimeBodyPart();
			msgMultipart.addBodyPart(attch1);
			
			//设置附件的名称
			attch1.setFileName("file1.BMP");
			//设置数据源(即数据的来源)
			DataSource ds1 = new FileDataSource("C:\\d.BMP");
			DataHandler dh1 = new DataHandler(ds1);
			//设置附件的句柄给这个附件对象
			attch1.setDataHandler(dh1);
			
			Transport transport = session.getTransport();
			transport.connect("smtp.yeah.net", 25, "用户名", "密码");
			transport.sendMessage(msg, new Address[]{new InternetAddress("[email protected]")});

			transport.close();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

 

这里根据邮件的内容需要配置邮件的类型,如图:(来自传智播客)

 

javamail添加附件

 

javamail添加附件

 

你可能感兴趣的:(javamail)