Spring 邮件发送详细配置

1. 引入所需要jar包:activation.jarcommons-logging.jarmail.jarspring相关jar

 

2. Spring底层采用java mail进行集成,封装成统一API方便调用,Spring xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:tool="http://www.springframework.org/schema/tool" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
	http://www.springframework.org/schema/beans/spring-beans.xsd  
	http://www.springframework.org/schema/tx  
	http://www.springframework.org/schema/tx/spring-tx.xsd  
	http://www.springframework.org/schema/aop  
	http://www.springframework.org/schema/aop/spring-aop.xsd  
	http://www.springframework.org/schema/jee  
	http://www.springframework.org/schema/jee/spring-jee.xsd  
	http://www.springframework.org/schema/context  
	http://www.springframework.org/schema/context/spring-context.xsd  
	http://www.springframework.org/schema/util  
	http://www.springframework.org/schema/util/spring-util.xsd  
	http://www.springframework.org/schema/tool  
	http://www.springframework.org/schema/tool/spring-tool.xsd
	http://www.springframework.org/schema/task 
	http://www.springframework.org/schema/task/spring-task.xsd
	http://www.springframework.org/schema/websocket 
	http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd
	http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
	
    <!-- 申明JavaMailSenderImpl对象 -->  
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
        <property name="defaultEncoding" value="UTF-8" />  
        <property name="host" value="smtp.exmail.qq.com" />  
        <property name="username" value="[email protected]" />  
        <property name="password" value="xxxxxxxxx" />  
        <property name="javaMailProperties">  
            <props>  
                <!-- 设置认证开关 -->
                <prop key="mail.smtp.auth">true</prop>  
                <!-- 启动调试开关 -->
                <prop key="mail.debug">true</prop>  
                <!-- 设置发送延时 -->
                <prop key="mail.smtp.timeout">0</prop>
            </props>  
        </property>  
    </bean>  
	
	
	
</beans>

 

3. 封装邮件发送接口

MailCriteria

import java.util.Date;

public class MailCriteria {

	private String mailType;//邮件类型(文本邮件,或者带附件邮件)
	private String from;
	private String replyTo;
	private String[] to;
	private String[] cc;
	private String[] bcc;
	private Date sentDate;
	private String title;
	private String content;
	private String fileUrl;

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getReplyTo() {
		return replyTo;
	}

	public void setReplyTo(String replyTo) {
		this.replyTo = replyTo;
	}

	public String[] getTo() {
		return to;
	}
	
	public void setTo(String to){
		this.to = new String[]{to};
	}

	public void setTo(String[] to) {
		this.to = to;
	}

	public String[] getCc() {
		return cc;
	}

	public void setCc(String[] cc) {
		this.cc = cc;
	}

	public String[] getBcc() {
		return bcc;
	}

	public void setBcc(String[] bcc) {
		this.bcc = bcc;
	}

	public Date getSentDate() {
		return sentDate;
	}

	public void setSentDate(Date sentDate) {
		this.sentDate = sentDate;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getFileUrl() {
		return fileUrl;
	}

	public void setFileUrl(String fileUrl) {
		this.fileUrl = fileUrl;
	}

	public String getMailType() {
		return mailType;
	}

	public void setMailType(String mailType) {
		this.mailType = mailType;
	}
}

 

IMailService

public interface IMailService {

	/**
	 * 发送邮件
	 * 目前只支持:文本邮件, 以及带单个附件的文本(需要时候可以扩展成多个附件)
	 * @param criteria
	 * @throws Exception
	 */
	public void sendEmail(MailCriteria criteria) throws Exception;
	
}

 MailServiceImpl

import java.net.URL;

import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamSource;
import org.springframework.core.io.UrlResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;


@Component
public class MailServiceImpl implements IMailService{

	private static Logger logger = Logger.getLogger(MailServiceImpl.class);
	
	@Autowired
	private JavaMailSenderImpl senderImpl;
	
	@Override
	public void sendEmail(MailCriteria criteria) throws Exception{
		
		if (Constants.MAIL_TYPE_TEXT.equals(criteria.getMailType())) {
			sendTextEmail(criteria);
		}
		else if (Constants.MAIL_TYPE_FILE.equals(criteria.getMailType())) {
			sendFileEmail(criteria);
		}
		else {
			throw new Exception("不支持该邮件类型发送>>>"+criteria.getMailType());
		}
	}
	
	/**
	 * 发送简单的文本邮件
	 */
	public void sendTextEmail(MailCriteria criteria) {
		try {
			SimpleMailMessage mailMessage = new SimpleMailMessage();
			
			if (StringUtil.isEmpty(criteria.getFrom())) {
				mailMessage.setFrom(senderImpl.getUsername());
			}
			else {
				mailMessage.setFrom(criteria.getFrom());
			}
			mailMessage.setTo(criteria.getTo());
			mailMessage.setSubject(criteria.getTitle());
			mailMessage.setText(criteria.getContent());
			
			// 发送邮件
			senderImpl.send(mailMessage);
			logger.info("邮件发送成功.. ");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发送简单的html邮件
	 */
	public void sendHtmlEmail(MailCriteria criteria) {
		try {
			// 建立邮件消息,发送简单邮件和html邮件的区别
			MimeMessage mailMessage = senderImpl.createMimeMessage();
			MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);
			
			// 设置收件人,寄件人
			if (StringUtil.isEmpty(criteria.getFrom())) {
				mailMessage.setFrom(senderImpl.getUsername());
			}
			else {
				mailMessage.setFrom(criteria.getFrom());
			}
			messageHelper.setTo(criteria.getTo());
			messageHelper.setSubject(criteria.getTitle());
			// true 表示启动HTML格式的邮件
			messageHelper.setText("<html><head></head><body><h1>"+criteria.getContent()+"</h1></body></html>",true);
			
			// 发送邮件
			senderImpl.send(mailMessage);
			logger.info("邮件发送成功..");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送嵌套图片的邮件(图片地址是采用URL方式)
	 */
	public void sendImageEmail(MailCriteria criteria) {
		try {
			 //建立邮件消息,发送简单邮件和html邮件的区别 
		    MimeMessage mailMessage = senderImpl.createMimeMessage(); 
		    //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,         
		    //multipart模式 
		    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true); 
		    
		    //设置收件人,寄件人 
		    if (StringUtil.isEmpty(criteria.getFrom())) {
		    	mailMessage.setFrom(senderImpl.getUsername());
			}
			else {
				mailMessage.setFrom(criteria.getFrom());
			}
		    messageHelper.setTo(criteria.getTo()); 
		    messageHelper.setSubject(criteria.getTitle()); 
		    //true 表示启动HTML格式的邮件 
		    messageHelper.setText("<html><head></head><body><h1>"+criteria.getContent()+"</h1><img src='cid:aaa'/></body></html>",true); 
		        
		   //FileSystemResource img = new FileSystemResource(new File("g:/123.jpg")); 
		    InputStreamSource iss = new UrlResource(new URL(criteria.getFileUrl()));
		    messageHelper.addInline("aaa",iss,"text/img");
		    
		    //发送邮件 
		    senderImpl.send(mailMessage); 
		    logger.info("邮件发送成功.."); 
		} catch (Exception e) {
			logger.info(e);
		}
	}
	
	/**
	 * 发送包含附件的邮件(附件的地址是采用URL方式)
	 */
	public void sendFileEmail(MailCriteria criteria) {
		InputStreamSource iss = null;
		try {
			//建立邮件消息,发送简单邮件和html邮件的区别 
		    MimeMessage mailMessage = senderImpl.createMimeMessage(); 
		    //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,         
		    //multipart模式 为true时发送附件 可以设置html格式
		    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8"); 
		    
		    //设置收件人,寄件人 
		    messageHelper.setTo(criteria.getTo());    
		    if (StringUtil.isEmpty(criteria.getFrom())) {
		    	messageHelper.setFrom(senderImpl.getUsername());
			}
			else {
				messageHelper.setFrom(criteria.getFrom());
			}
		    messageHelper.setSubject(criteria.getTitle()); 
		    //true 表示启动HTML格式的邮件 
		    messageHelper.setText("<html><head></head><body><h1>"+criteria.getContent()+"</h1></body></html>",true); 
		    
		    iss = new UrlResource(new URL(criteria.getFileUrl()));
		    String prefix = criteria.getFileUrl().substring(criteria.getFileUrl().lastIndexOf(".")+1);
		    //这里的方法调用和插入图片是不同的。 
		    messageHelper.addAttachment("test."+prefix,iss); 
		    
		    //发送邮件 
		    senderImpl.send(mailMessage); 
		    logger.info("邮件发送成功.."); 
		} catch (Exception e) {
			logger.info(e);
		} finally {
			try {
				iss.getInputStream().close();
			} catch (Exception e) {
				logger.info(e);
			}
		}
	}
}

 

4. 客户端调用

 

首先实例化对象:MailCriteria

 

其次实例化对象:MailServiceImpl

 

接着调用:sendEmail

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(spring)