用javaapi发送邮件

关键字: javamail, 邮件

1、MimeMessage的包装类
Java代码 复制代码
  1. public class SimpleMessageWraper {   
  2.     private Session session;   
  3.     private MimeMessage mimeMessage;   
  4.     private Multipart multipart = new MimeMultipart();;   
  5.        
  6.     public Session getSession() {   
  7.         return session;   
  8.     }   
  9.   
  10.     public MimeMessage getMimeMessage() {   
  11.         return mimeMessage;   
  12.     }   
  13.        
  14.     private String arrayToString(String[] array){   
  15.         String s = "";   
  16.         if(array != null && array.length > 0){   
  17.             for(int i=0;i<array.length;i++){   
  18.                 if(s == ""){   
  19.                     s = array[i].trim();   
  20.                 }else{   
  21.                     s += "," + array[i].trim();   
  22.                 }   
  23.             }   
  24.         }   
  25.         return s;   
  26.     }   
  27.        
  28.     public SimpleMessageWraper(Properties props){   
  29.         session = Session.getInstance(props);   
  30.         session.setDebug(false);   
  31.            
  32.         mimeMessage = new MimeMessage(session);   
  33.     }   
  34.        
  35.     public void setFrom(String from)throws MessagingException{   
  36.         mimeMessage.setFrom(new InternetAddress(from));   
  37.         mimeMessage.saveChanges();   
  38.     }   
  39.        
  40.     public void setTo(String[] toArray)throws MessagingException{   
  41.         String s = arrayToString(toArray);   
  42.         Address[] addresses = InternetAddress.parse(s);   
  43.         mimeMessage.setRecipients(Message.RecipientType.TO, addresses);   
  44.         mimeMessage.saveChanges();   
  45.     }   
  46.        
  47.     public void setCc(String[] ccArray)throws MessagingException{   
  48.         String s = arrayToString(ccArray);   
  49.         Address[] addresses = InternetAddress.parse(s);   
  50.         mimeMessage.setRecipients(Message.RecipientType.CC, addresses);   
  51.         mimeMessage.saveChanges();   
  52.     }   
  53.        
  54.     public void setSubject(String subject)throws MessagingException{   
  55.         mimeMessage.setSubject(subject);   
  56.         mimeMessage.saveChanges();   
  57.     }   
  58.        
  59.     public void setSentDate(Date date)throws MessagingException{   
  60.         mimeMessage.setSentDate(date);   
  61.         mimeMessage.saveChanges();   
  62.     }   
  63.   
  64.     public void setText(String text)throws MessagingException{   
  65.         MimeBodyPart mimeBodyPart = new MimeBodyPart();    
  66.         mimeBodyPart.setText(text);   
  67.         multipart.addBodyPart(mimeBodyPart);   
  68.         mimeMessage.setContent(multipart);   
  69.         mimeMessage.saveChanges();   
  70.     }   
  71.        
  72.     public void addAttactment(File file)throws MessagingException,UnsupportedEncodingException{   
  73.         if(file == nullreturn;   
  74.            
  75.         MimeBodyPart mimeBodyPart = new MimeBodyPart();    
  76.         mimeBodyPart.setFileName(MimeUtility.encodeText(file.getName(), "GBK""B")); //对邮件头采用base64方式编码   
  77.         mimeBodyPart.setDataHandler(new DataHandler(new FileDataSource(file)));    
  78.         multipart.addBodyPart(mimeBodyPart);    
  79.         mimeMessage.setContent(multipart);   
  80.         mimeMessage.saveChanges();   
  81.     }   
  82. }  
public class SimpleMessageWraper {
	private Session session;
	private MimeMessage mimeMessage;
	private Multipart multipart = new MimeMultipart();;
	
	public Session getSession() {
		return session;
	}

	public MimeMessage getMimeMessage() {
		return mimeMessage;
	}
	
	private String arrayToString(String[] array){
		String s = "";
		if(array != null && array.length > 0){
			for(int i=0;i<array.length;i++){
				if(s == ""){
					s = array[i].trim();
				}else{
					s += "," + array[i].trim();
				}
			}
		}
		return s;
	}
	
	public SimpleMessageWraper(Properties props){
        session = Session.getInstance(props);
        session.setDebug(false);
        
		mimeMessage = new MimeMessage(session);
	}
	
	public void setFrom(String from)throws MessagingException{
		mimeMessage.setFrom(new InternetAddress(from));
        mimeMessage.saveChanges();
	}
	
	public void setTo(String[] toArray)throws MessagingException{
		String s = arrayToString(toArray);
		Address[] addresses = InternetAddress.parse(s);
		mimeMessage.setRecipients(Message.RecipientType.TO, addresses);
        mimeMessage.saveChanges();
	}
	
	public void setCc(String[] ccArray)throws MessagingException{
		String s = arrayToString(ccArray);
		Address[] addresses = InternetAddress.parse(s);
		mimeMessage.setRecipients(Message.RecipientType.CC, addresses);
        mimeMessage.saveChanges();
	}
	
	public void setSubject(String subject)throws MessagingException{
		mimeMessage.setSubject(subject);
        mimeMessage.saveChanges();
	}
	
	public void setSentDate(Date date)throws MessagingException{
		mimeMessage.setSentDate(date);
        mimeMessage.saveChanges();
	}

    public void setText(String text)throws MessagingException{
    	MimeBodyPart mimeBodyPart = new MimeBodyPart(); 
    	mimeBodyPart.setText(text);
    	multipart.addBodyPart(mimeBodyPart);
    	mimeMessage.setContent(multipart);
        mimeMessage.saveChanges();
    }
    
    public void addAttactment(File file)throws MessagingException,UnsupportedEncodingException{
    	if(file == null) return;
    	
    	MimeBodyPart mimeBodyPart = new MimeBodyPart(); 
    	mimeBodyPart.setFileName(MimeUtility.encodeText(file.getName(), "GBK", "B")); //对邮件头采用base64方式编码
    	mimeBodyPart.setDataHandler(new DataHandler(new FileDataSource(file))); 
    	multipart.addBodyPart(mimeBodyPart); 
    	mimeMessage.setContent(multipart);
        mimeMessage.saveChanges();
    }
}


2、发送邮件的工具类
Java代码 复制代码
  1. public class SimpleMailFactory {   
  2.     private static SimpleMailConfig simpleMailConfig = null;   
  3.     private static Properties props = null;   
  4.        
  5.     static{   
  6.         //取得包含邮件配置信息的bean对象   
  7.         simpleMailConfig = (SimpleMailConfig)SpringContextUtil.getBean(Constants.simpleMailConfigBeanName);   
  8.            
  9.         props = new Properties();   
  10.         props.put("mail.smtp.host", simpleMailConfig.getHost());   
  11.         props.put("mail.smtp.auth", simpleMailConfig.getAuth());   
  12.     }   
  13.        
  14.     /**  
  15.      * 功能:取得邮件消息对象的包装器  
  16.      */  
  17.     public static SimpleMessageWraper getSimpleMessageWraper(){   
  18.         return new SimpleMessageWraper(props);   
  19.     }   
  20.   
  21.     /**  
  22.      * 功能:邮件发送  
  23.      */  
  24.     public static void send(SimpleMessageWraper messageWraper)throws Exception{   
  25.         MimeMessage mimeMessage = messageWraper.getMimeMessage();   
  26.         Transport transport = messageWraper.getSession().getTransport(simpleMailConfig.getTransport());   
  27.            
  28.         transport.connect(simpleMailConfig.getHost(), simpleMailConfig.getUsername(), simpleMailConfig.getPassword());   
  29.         transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());   
  30.         transport.close();           
  31.     }   
  32. }  
public class SimpleMailFactory {
	private static SimpleMailConfig simpleMailConfig = null;
	private static Properties props = null;
	
	static{
	    //取得包含邮件配置信息的bean对象
		simpleMailConfig = (SimpleMailConfig)SpringContextUtil.getBean(Constants.simpleMailConfigBeanName);
		
		props = new Properties();
        props.put("mail.smtp.host", simpleMailConfig.getHost());
        props.put("mail.smtp.auth", simpleMailConfig.getAuth());
	}
	
	/**
	 * 功能:取得邮件消息对象的包装器
	 */
	public static SimpleMessageWraper getSimpleMessageWraper(){
		return new SimpleMessageWraper(props);
	}

	/**
	 * 功能:邮件发送
	 */
	public static void send(SimpleMessageWraper messageWraper)throws Exception{
		MimeMessage mimeMessage = messageWraper.getMimeMessage();
        Transport transport = messageWraper.getSession().getTransport(simpleMailConfig.getTransport());
        
        transport.connect(simpleMailConfig.getHost(), simpleMailConfig.getUsername(), simpleMailConfig.getPassword());
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();        
	}
}


3、包含邮件配置信息的bean对象
Xml代码 复制代码
  1. <bean id="simpleMailConfig" class="com.cjm.common.mail.SimpleMailConfig">  
  2.     <property name="host" value="smtp.163.com"/>  
  3.     <property name="username" value="uid"/>  
  4.     <property name="password" value="pwd"/>  
  5.     <property name="auth" value="true"/>  
  6. </bean>  


4、实例代码
Java代码 复制代码
  1. SimpleMessageWraper w1 = SimpleMailFactory.getSimpleMessageWraper();   
  2. w1.setFrom("ServerMailAddress@163.com");   
  3. w1.setTo(new String[]{"TargetAddress@139.com"});   
  4. w1.setSubject("标题");   
  5. w1.setText("邮件内容");   
  6. w1.addAttactment(new File("c://附件.txt"));   
  7. SimpleMailFactory.send(w1);  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值