用Spring的邮件抽象层发送邮件

1、MimeMessageHelper包装类
public class MessageWraper {
	private MimeMessage message;
	private MimeMessageHelper messageHelper;
	
	public MimeMessage getMessage() {
		return message;
	}

	public MimeMessageHelper getMessageHelper() {
		return messageHelper;
	}

	public MessageWraper(MimeMessage message, MimeMessageHelper messageHelper){
		this.message = message;
		this.messageHelper = messageHelper;
	}
	
	public void setFrom(String from)throws MessagingException{
		messageHelper.setFrom(from);
	}
	
	public void setTo(String[] toArray)throws MessagingException{
		messageHelper.setTo(toArray);
	}
	
	public void setCc(String[] ccArray)throws MessagingException{
		messageHelper.setCc(ccArray);
	}
	
	public void setSubject(String subject)throws MessagingException{
		messageHelper.setSubject(subject);
	}
	
	public void setText(String text, boolean isHtml)throws MessagingException{
		messageHelper.setText(text, isHtml);
	}
	
	public void setText(String text)throws MessagingException{
		messageHelper.setText(text, false);
	}
	
	public void setSentDate(Date date)throws MessagingException{
		if(date == null) date = new Date();
		messageHelper.setSentDate(date);
	}
	
	public void addAttachment(File file)throws MessagingException,UnsupportedEncodingException{
		if(file == null) return;
		String fileName = MimeUtility.encodeText(file.getName(), Constants.mailEncoding, null);
		messageHelper.addAttachment(fileName, file);
	}
}


2、发送邮件的工具类
public class MailFactory {
	private static JavaMailSender javaMailSender = null;
	
	static{
		javaMailSender = (JavaMailSender)SpringContextUtil.getBean("mailConfig");
	}
	
	/**
	 * 功能:获取邮件消息对象的包装类
	 */
	public static MessageWraper getMessageWraper()throws MessagingException{
		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
		MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, Constants.mailEncoding); //multipart模式
		
		return new MessageWraper(mimeMessage, mimeMessageHelper);
	}
	
	/**
	 * 功能:发送邮件
	 * 
	 * @param messageWraper 消息对象的包装类对象
	 */
	public static void send(MessageWraper messageWraper) throws Exception{
		javaMailSender.send(messageWraper.getMessage()); 		
	}
}


3、包含邮件配置信息的bean
<bean id="mailConfig" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	<property name="host" value="smtp.163.com"/>
	<property name="username" value="uid"/>
	<property name="password" value="pwd"/>
	<property name="javaMailProperties">
		<props>
			<prop key="mail.smtp.auth">true</prop>
		</props>
	</property>
</bean>


4、实例代码
MessageWraper w2 = MailFactory.getMessageWraper();
w2.setFrom("[email protected]");
w2.setTo(new String[]{"[email protected]"});
w2.setSubject("标题");
w2.setText("邮件内容");
w2.addAttachment(new File("d:\\附件.txt"));
MailFactory.send(w2);

你可能感兴趣的:(spring,bean,xml)