Java Mail实现带附件的邮件发送

简单附件发送见我另一博客:

http://blog.csdn.net/vandic/article/details/7674800

 

实现带附件的邮件发送其实很简单,Java Mail提供了一个MimeMultipart,用户可以往MimeMultipart加入不同的内容,如文字部分和附件部分等,多个附件循环加入即可。更多内容可查看官方API:http://javamail.kenai.com/nonav/javadocs/

 

 

public boolean sendMail(){      
      
      
    Session session=getSession();  
    boolean result = false;  
    //内容编码  
    String mailtype = "text/html;charset=GBK";  
    try{  
         
        MimeMessage msg = new MimeMessage(session);  
        msg.setFrom(new InternetAddress("[email protected]"));//发送邮箱
            
        InternetAddress[] tos = new InternetAddress[1];//收件箱
        tos[0] = new InternetAddress("[email protected]");
         
        
        //基本信息
        msg.setRecipients(RecipientType.TO, tos);  
        msg.setSubject("这是一个测试邮件。");  
        
        //文字部分
        MimeMultipart multipart = new MimeMultipart("mixed");
        BodyPart msgBodyPart = new MimeBodyPart();
        msgBodyPart.setContent("这个邮件有附件哟~", mailtype);
        multipart.addBodyPart(msgBodyPart);
       

        //附件部分
	BodyPart attBodyPart = new MimeBodyPart();
	DataSource ds= new FileDataSource(new File("f:\\attachment\\itilbase_user_guide.pdf"));
		
	attBodyPart.setDataHandler(new DataHandler(ds));
	attBodyPart.setFileName(MimeUtility.encodeText(ds.getName()));
	multipart.addBodyPart(attBodyPart);
	msg.setContent(multipart);
        
        
        
        Transport.send(msg);  
        result = true;  
    } catch (Exception e){     
       e.printStackTrace();  
    }  
      
    return result;  
}  



你可能感兴趣的:(发送邮件,java mail,java发邮件,java邮件)