`
strongant
  • 浏览: 64896 次
  • 性别: Icon_minigender_1
  • 来自: IT
社区版块
存档分类
最新评论

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="8673711@qq.com" />  
        <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实现各种邮件的发送

    Spring实现各种邮件的发送 简单配置就可发送邮件

    Spring Boot整合邮件发送并保存历史发送邮箱

    Spring Boot整合邮件发送并保存历史发送邮箱 项目描述 项目主要是使用 Spring Boot 发送邮件,主要的技术点有: 1、Spring Boot +mybatis的整合 2、Spring Boot项目中jsp的使用 3、Spring Boot 发送邮件...

    Spring mvc 发送邮件功能

    基于spring mvc 框架,用freemarker创建邮件模板,包括详细邮件发送功能的spring配置和实现代码

    spring-boot-邮件发送

    Spring Boot通过集成spring-boot-starter-mail依赖和相关配置,可以方便地实现邮件发送功能。具体的步骤: 添加依赖:在Spring Boot项目的pom.xml文件中加入spring-boot-starter-mail依赖,如果需要发送模板邮件,还...

    struts2+spring3.0+mybatis3.0.4集成的邮件发送实例(可上传附件)

    数据库:sqlserver CreateHtmlTable中的生成路径和SendService中的上传路径改成自己的

    基于Spring的邮件发送系统设计源码

    Spring邮件发送系统:基于Java构建,包含67个文件,包括60个XML配置文件、3个Java类文件、2个.gitignore文件、1个Idea项目文件(.iml)和1个YAML配置文件。该项目是一个Spring email的最简单入门案例,用于演示如何...

    Spring配置的邮件发送

    用组件做的一个小应用,加了点spring的小功能,依赖注射 方便配置

    Spring Boot邮件发送(powernode document)(源代码)

    Spring Boot邮件发送(powernode document)(源代码) 1.概述 2.最佳实践 2.1创建项目引入依赖(mail) 2.2修改yml配置文件 2.3编写测试发送邮件 2.4 测试结果 2.4.1 发送基本内容 2.4.2 发送复杂内容 我们使用java...

    采用 spring 发送带 附件的邮件(完整示例,带 jar 包)

    本例为完整的采用spring 发送带 附件的邮件。 下载后需要改动的地方: 1.在mail.properties中将接收者邮箱地址(username),邮箱密码换成真实的。 2.在SpringJavaMailDemo类中把发送者和接收者邮箱地址换成真实地址...

    编程语言+JAVAspring+邮件服务+邮件发送

    编程语言+JAVAspring+邮件服务+邮件发送**:这是一个关于JAVAspring编程语言的邮件服务的邮件发送的资源,适合有一定JAVAspring基础的开发者。它介绍了JAVAspring的邮件服务的概念、原理和作用,以及如何使用JAVA...

    Spring Boot邮件发送(powernode CD2207)(教学视频+源代码)

    Spring Boot邮件发送(powernode CD2207)(教学视频+源代码) SpringBoot提供了发送邮件的功能 SpringBoot实现邮件功能是非常的方便快捷的,因为SpringBoot默认有starter实现了Mail。 发送邮件应该是网站的必备功能...

    spring整合quartz定时发送邮件

    该文档写了spring结合quartz定时发送邮件,有详细的配置文件,和相关代码,稍加研究就可以运行。

    spring-boot-mail

    spring boot 邮件发送,亲测可用 #字符集 spring.mail.default-encoding=UTF-8 #电子邮件地址 spring.mail.host=smtp.126.com #Application spring.application.name=SEND-MAIL #授权密码 spring.mail.password=...

    spring发送邮件

    本文档主要是讲述使用spring自带的邮件发送功能,以配置文件的方式来完成

    Spring Cloud alibaba 集成 SkyWalking 日志 以及告警邮件

    使用邮件请在gateway模块配置文件中配置自己的邮箱信息 跟着课件学习的,启动服务可能需要关联启动:nacos sentinel seata skywalking其中某些中间件 配合博客...

    Spring Boot整合JavaMailSender发送电子邮件

    Spring提供了非常好用的JavaMailSender接口实现邮件发送。在Spring Boot的Starter模块中也为此提供了自动化配置。下面通过实例看看如何在Spring Boot中使用JavaMailSender发送邮件。

    Spring javaMail发送文本邮件实例

    导入到Myeclipse 即可运行 测试使用的是QQ邮箱 在application.xml中配置的发送邮箱 要到邮箱中设置 POP3/SMTP服务为开。项目不部署到tomcat后启动服务,然后运行test.java 就发送了,。绝对可以发送

    使用spring实现邮件的发送实例(含测试,源码,注释)

    本篇文章主要介绍了使用spring实现邮件的发送实例,详细的介绍了使用spring配置实现邮件发送,含测试,源码,注释,有兴趣的可以下

    Spring编写的发邮件程序,带定时功能

    我自己从pro spring书上修改过来的发邮件程序,在配置文件javaMailSender.xml中把自己邮箱的地址,用户名,密码,发送邮件的服务器修改一下就能使用了。 此邮件程序还有定时功能,到你定的时刻后它就开始发邮件,...

Global site tag (gtag.js) - Google Analytics