spring框架之邮件发送

Spring发送邮件的相关配置及程序:引入相应的jar包,同时可能会出现一个错误--
java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream

这是由于JAVAEE5中的javaee.jar中的mail和mail.jar冲突导致的,解决的方法是将Library改成J2EE 1.4 Libraries就行了.
   
<!-- 发送email的配置. -->
<bean id="mailSender"
	class="org.springframework.mail.javamail.JavaMailSenderImpl">
	<property name="host" value="smtp.163.com"></property>
	<property name="javaMailProperties">
		<props>
			<prop key="mail.smtp.auth">true</prop>
			<prop key="mail.smtp.timeout">25000</prop>
			<prop key="mail.transport.protocol">smtp</prop>
			<prop key="mail.smtp.auth">true</prop>
			<prop key="mail.smtp.starttls.enable">true</prop>
		</props>
	</property>
	<property name="username" value="*********@163.com" />
	<property name="password" value="*********" />
</bean>


其中username和password指的是发送端的邮箱用户名和密码。

package com.demo.cyd.service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;


public class SendEmailImpl {

	public ApplicationContext ctx = null;  

	public SendEmailImpl() {  
	  //获取上下文  
	  ctx = new ClassPathXmlApplicationContext("beans.xml");  

	 }  

	 public void sendMail(String emailto,String content) throws MessagingException {  
		 //获取JavaMailSender bean  
		  JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");  

		  
		  JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();  
		  MimeMessage mailMessage = senderImpl.createMimeMessage();  
		  //设置utf-8或GBK编码,否则邮件会有乱码  
		  MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");  
		  try {  
			   messageHelper.setTo(emailto);//接受者    
			   messageHelper.setFrom("[email protected]");//发送者
			   messageHelper.setSubject("站点目录异常,请检查!");//主题  
			   //邮件内容,注意加参数true,表示启用html格式  
			   messageHelper.setText(content,true); 
			   sender.send(mailMessage);  
		
		  } catch (Exception e) {  
			  e.printStackTrace();  
		  }  
	}
	 public static void main(String[] args) throws MessagingException {
		String emailto = "[email protected]";
		String context = "***万岁!<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head><body><h1><a href='http://www.baidu.com'>郁闷!</a></h1></body></html>";
		SendEmailImpl service = new SendEmailImpl();
		service.sendMail(emailto, context);
	}
}


你可能感兴趣的:(spring)