spring mail demo

//修改用户名密码即可,提示:有些邮箱不支持smtp,请大家多换几个试试,spring mail 服务配置进来
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  		<property name="host" value="smtp.163.com" /> 
  		<property name="port" value="25" /> 
  		<property name="username" value="****@163.com" /> 
  		<property name="password" value="*******" /> 
		<property name="javaMailProperties">
			<props>
	  			<prop key="mail.smtp.auth">true</prop> 
	  			<prop key="mail.smtp.timeout">25000</prop> 
	  		</props>
  		</property>
  	</bean>
	// 邮件模板
	<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
	 <property name="resourceLoaderPath" value="WEB-INF/"></property>
	<!-- 
		<property name="velocityProperties">
	  		<value>resource.loader=class class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</value> 
	  	</property>
	 -->
  	</bean>

// 将发送邮件和邮件模板都注入到需要发送邮件的业务层类

<bean id="**Service" class="****.service.impl.***">
		<property name="***DAO">
			<ref bean="***DAO"/>
		</property>
		<property name="mailSender" ref="mailSender" /> 
  		<property name="velocityEngine" ref="velocityEngine" /> 
	</bean>



业务层方法
public boolean sendEmail(final User user) {
		System.out.println("user.email===="+user.getEmail());
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
		        MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true,"UTF-8");
				message.setSubject("标题");
				message.setTo(user.getEmail());
				message.setFrom("***@163.com");
				Map model = new HashMap();
				model.put("user", user);
				String text = VelocityEngineUtils.mergeTemplateIntoString(
		    	velocityEngine, "registration-confirmation.vm","UTF-8", model);
		        message.setText(text, true);
		    }
		};
		try{
			this.mailSender.send(preparator);
			return true;
		}catch(MailException e) {
			System.out.println("没有这个邮箱");
			return true;
		}
	}
//将模板registration-confirmation.vm 存放在resourceLoaderPath的配置路径下(WEB-INF/) 模板见附件
//依赖javamail.jar,   j2ee4和j2ee5也有关系,使用时注意

你可能感兴趣的:(apache,spring,Web,velocity)