利用spring中的mail发送邮件

一、
使用spring已封装的邮件发送实现类,配置属性,其中smtp.ym.163.com为企业邮箱的smtp地址
引用
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <property name="host" value="smtp.ym.163.com"/>
  <property name="javaMailProperties">
         <props>
  <prop key="mail.debug">true</prop>
  <prop key="mail.smtp.auth">true</prop>
  <prop key="mail.transport.protocol">smtp</prop>
  </props>
  </property>
  <property name="username" value="[email protected]"/>
  <property name="password" value="123456"/>
</bean>


定义一个邮件发送模版
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
        <property name="from" value="[email protected]"/>
	<property name="subject" value="Your order"/>
</bean>


实现发送逻辑
        @Autowired
	private JavaMailSender mailSender;
	@Autowired
        private SimpleMailMessage templateMessage;
	@Autowired
	private VelocityEngine velocityEngine;
	
	@Override
	public void sendEmail() {
		  SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
	        msg.setTo("[email protected]");
	        msg.setText(
	            "注册信息");
	        try{
	            this.mailSender.send(msg);
	        }
	        catch(MailException ex) {
	            System.err.println(ex.getMessage());            
	        }
	}


二、
自定义一个邮件模版文件,使用velocity解析
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  	<property name="host" value="smtp.ym.163.com"/>
  	<property name="javaMailProperties">
  		<props>
  			<prop key="mail.debug">true</prop>
  			<prop key="mail.smtp.auth">true</prop>
  			<prop key="mail.transport.protocol">smtp</prop>
  		</props>
  	</property>
  	<property name="username" value="[email protected]"/>
  	<property name="password" value="123456"/>
  	<property name="defaultEncoding" value="utf-8"></property>
</bean>


定义velocity引擎
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
	<property name="velocityProperties">
		   <value>
		          resource.loader=class
		        class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
		   </value>
         </property>
</bean>



实现发送逻辑
	@Override
	public void sendEmailTemplate(final User user) {
		MimeMessagePreparator mmp = new MimeMessagePreparator() {
			@Override
			public void prepare(MimeMessage mimeMessage) throws Exception {
				 MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
		            message.setTo(user.getEmailAddress());
		            message.setFrom("[email protected]"); 
		            Map model = new HashMap();
		            model.put("user", user);
		            String text = VelocityEngineUtils.mergeTemplateIntoString(
		               velocityEngine, "just/my/mail.html", model);
		            System.out.println(text);
		            message.setText(text, true);
			}
		};
		this.mailSender.send(mmp);
	}

你可能感兴趣的:(Spring email)