springboot集成发送邮件、短信的小测试demo

   在我们工作中,遇到很多系统都有关于注册发送短信或者邮箱验证这一个功能,同样的springboot也集成了这一块,那么我就简单的写一个demo测试一下,实际工作中会有很多权限控制,安全校验等,这个demo只是让我们知道springboot如何处理这一块的逻辑,方便我们入手。首先,看一下我的项目的结构图:

springboot集成发送邮件、短信的小测试demo_第1张图片

pom文件:


	4.0.0
	com.csq.study
	springBoot-sendMail
	0.0.1-SNAPSHOT
	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.2.RELEASE
	
	
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter
		
		
		
			org.springframework.boot
			spring-boot-starter-mail
		
		
		
			org.springframework.boot
			spring-boot-starter-thymeleaf
		
		
		
			org.springframework.boot
			spring-boot-starter-web
		
			
            commons-logging
            commons-logging
            1.1.1
        

        
            commons-codec
            commons-codec
            1.4
        

        
            commons-httpclient
            commons-httpclient
            3.0.1
        
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	
	

配置文件:

#设置服务端口
server.port=8088
# Email配置属性
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
[email protected]
#切记此处需要开启pom3的时候的验证码不是邮箱的密码
spring.mail.password=#验证码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

mail1.html




    
    邮件格式


    

,你好!

这是一封测试邮件。

mail2.html




    
    测试邮件2


    

,你好!

这是一封含有附件的邮件,请查收!

 

controller:

SendMailController 

package com.csq.study.springboot.sendmail.controller;

import java.io.File;
import java.util.ArrayList;

import javax.mail.MessagingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.csq.study.springboot.sendmail.service.SendMailService;

@RestController
public class SendMailController {
	@Autowired
    private SendMailService sendMailService;

    @Autowired
    private TemplateEngine templateEngine;
    @GetMapping("/sendOne")
    public String sendOne() throws MessagingException {
        //简单邮件
        //测试企业邮箱
    	sendMailService.sendTxtMail1("****[email protected]","简单的文字介绍","我是一封简单的测试邮件");
    	  return "sendOne发送成功";
    }
    @GetMapping("/sendTwo")
    public String sendTwo() throws MessagingException {
        //模板邮件
        //测试163邮箱
        Context ct = new Context();
        ct.setVariable("username","我是托尼老师");
        sendMailService.sendTxtMail2("m186056****[email protected]","附带标题内容等邮件",templateEngine.process("mail/mail",ct));
        return "sendTwo发送成功";
    }
    @GetMapping("/sendThree")
    public String sendThree() throws MessagingException {
        //模板邮件,带附件
        Context ct = new Context();
        ct.setVariable("username","我是托尼老师(附带两首诗歌)");
        ArrayList files = new ArrayList<>();
        files.add(new File("C:\\Users\\Administrator\\Desktop\\love.txt"));
        sendMailService.sendTxtMail3("124346****@qq.com","带有附件的测试邮件",templateEngine.process("mail/mail2",ct),files);
        return "sendThree发送成功";
}
}

SendMessageController

package com.csq.study.springboot.sendmail.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.csq.study.springboot.sendmail.util.SendMessageUtil;
/**
 * 发送短信验证码
 * @Description: TODO 
 * @ClassName: SendMessageController
 * @author chengshengqing
 * @see TODO
 */
@RestController
public class SendMessageController {

	@GetMapping("/sendMessage")
    public String testSendMessage(){
//        SendMessageUtil.send("SMS账户","接口秘钥","目标号码","发送内容");
        Integer resultCode = SendMessageUtil.send("愤怒的清哥哥","d41d8cd98f00b204****","176006****5","验证码:"+SendMessageUtil.getRandomCode(6));
        return SendMessageUtil.getMessage(resultCode);
    }
    
   
}

service接口以及实现类

package com.csq.study.springboot.sendmail.service;

import java.io.File;
import java.util.List;

import javax.mail.MessagingException;
/**
 * 
 * @Description: TODO 
 * @ClassName: SendService
 * @author chengshengqing
 * @see TODO
 */
public interface SendMailService {
	/**
	 * 简单的邮件发送
	 * @Title: sendTxtMail1 
	 * @Description: TODO 
	 * @param accept
	 * @param topic
	 * @param content
	 * @author chengshengqing
	 */
	public void sendTxtMail1(String accept, String topic, String content) ;
	/**
	 * 附带标题等内容的邮件
	 * @Title: sendTxtMail2 
	 * @Description: TODO 
	 * @param accept
	 * @param topic
	 * @param content
	 * @throws MessagingException
	 * @author chengshengqing
	 */
	public void sendTxtMail2(String accept, String topic, String content) throws MessagingException;
	/**
	 * 附带附件的邮件
	 * @Title: sendTxtMail3 
	 * @Description: TODO 
	 * @param accept
	 * @param topic
	 * @param content
	 * @param files
	 * @throws MessagingException
	 */
	public void sendTxtMail3(String accept, String topic, String content, List files) throws MessagingException;
}

实现类

package com.csq.study.springboot.sendmail.service;

import java.io.File;
import java.util.List;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
public class SendMailServiceImpl implements SendMailService {

	
	@Autowired
    private JavaMailSender javaMailSender;
	
	/**
     * 邮件的发送方
     */
    @Value("${spring.mail.username}")
    private String sendFrom;
  
    /**
     * 发送一个简单测试
     *
     * @param accept  接收方
     * @param topic   邮件主题
     * @param content 邮件内容
     */
	@Override
	public void sendTxtMail1(String accept, String topic, String content) {
		// TODO Auto-generated method stub
		SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sendFrom);
        message.setTo(accept);
        message.setSubject(topic);
        message.setText(content);

        javaMailSender.send(message);
	}
	 /**
     * 发送含有标题内容等的邮件
     *
     * @param accept  接收方
     * @param topic   邮件主题
     * @param content 邮件内容
     * @throws MessagingException
     */
	@Override
	public void sendTxtMail2(String accept, String topic, String content) throws MessagingException {
		// TODO Auto-generated method stub
		 MimeMessage message = javaMailSender.createMimeMessage();
	        //true表示需要创建一个multipart message
	        MimeMessageHelper helper = new MimeMessageHelper(message, true);
	        helper.setFrom(sendFrom);
	        helper.setTo(accept);
	        helper.setSubject(topic);
	        helper.setText(content, true);

	        javaMailSender.send(message);
	}
	 /**
     * 发送含有标题内容且可以带附件等的邮件
     *
     * @param accept  接收方
     * @param topic   邮件主题
     * @param content 邮件内容
     * @param files   附带文件(可以多个文件)
     * @throws MessagingException
     */
	@Override
	public void sendTxtMail3(String accept, String topic, String content, List files)
			throws MessagingException {
		  // TODO Auto-generated method stub
		    MimeMessage message = javaMailSender.createMimeMessage();
	        MimeMessageHelper mh = new MimeMessageHelper(message, true);
	        mh.setFrom(sendFrom);
	        mh.setTo(accept);
	        mh.setSubject(topic);
	        mh.setText(content, true);
	        //添加附件
	        for(File file : files){
	        	mh.addAttachment(file.getName(), new FileSystemResource(file));
	        }

	        javaMailSender.send(message);
	    }
	}


 

工具类:

package com.csq.study.springboot.sendmail.util;

import java.util.Random;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

public class SendMessageUtil {

	    private static final String SMS_Url = "http://sms.webchinese.cn/web_api/";

	    /**
	     * @param Uid SMS用户id  :愤怒的清哥哥
	     * @param Key 接口秘钥:SMS登录可查(非登录密码)
	     * @param sendPhoneNum 短信发送目标号码
	     * @param desc 短信内容
	     * @return Integer(1:成功码,其他失败,具体参见注释)
	     */
	    public static Integer send(String Uid,String Key,String sendPhoneNum,String desc){

	        HttpClient client = new HttpClient();
	        PostMethod post = new PostMethod(SMS_Url);
	        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码

	        //设置参数
	        NameValuePair[] data = {
	                new NameValuePair("Uid", Uid),
	                new NameValuePair("Key", Key),//秘钥
	                new NameValuePair("smsMob", sendPhoneNum),
	                new NameValuePair("smsText", desc)
	        };

	        post.setRequestBody(data);

	        try {
	            client.executeMethod(post);
	        } catch (Exception e) {  e.printStackTrace();  }


	        Header[] headers = post.getResponseHeaders();
	        int statusCode = post.getStatusCode();
	        System.out.println("statusCode:" + statusCode);
	        for (Header h : headers) {
	            System.out.println(h.toString());
	        }

	        String result ="";
	        try {
	            result = new String(post.getResponseBodyAsString().getBytes("gbk"));
	        } catch (Exception e) {  e.printStackTrace();  }

	        post.releaseConnection();

	        return Integer.parseInt(result);
	    }
	    /**
	     *  -1  没有该用户账户
	     -2 接口密钥不正确 [查看密钥]不是账户登陆密码
	     -21    MD5接口密钥加密不正确
	     -3 短信数量不足
	     -11    该用户被禁用
	     -14    短信内容出现非法字符
	     -4 手机号格式不正确
	     -41    手机号码为空
	     -42    短信内容为空
	     -51    短信签名格式不正确接口签名格式为:【签名内容】
	     -6 IP限制
	     大于0    短信发送数量
	     以上作为补充
	     */
	    public static String getMessage(Integer code){
	        String message;
	        if(code > 0 ) {
	            message = "SMS-f发送成功!短信量还有" + code + "条";
	        }else if(code == -1){
	            message = "SMS-没有该用户账户";
	        }else if(code == -2){
	            message = "SMS-接口密钥不正确";
	        }else if(code == -21){
	            message = "SMS-MD5接口密钥加密不正确";
	        }else if(code == -3){
	            message = "SMS-短信数量不足";
	        }else if(code == -11){
	            message = "SMS-该用户被禁用";
	        }else if(code == -14){
	            message = "SMS-短信内容出现非法字符";
	        }else if(code == -4){
	            message = "SMS-手机号格式不正确";
	        }else if(code == -41){
	            message = "SMS-手机号码为空";
	        }else if(code == -42){
	            message = "SMS-短信内容为空";
	        }else if(code == -51){
	            message = "SMS-短信签名格式不正确接口签名格式为:【签名内容】";
	        }else if(code == -6){
	            message = "SMS-IP限制";
	        }else{
	            message = "其他错误";
	        }
	        return message;
	    }

	    /**
	     * 随机生成6位验证码
	     * @return
	     */
	    public static String getRandomCode(Integer code){
	        Random random = new Random();
	        StringBuffer result= new StringBuffer();
	        for (int i=0;i

启动类

package com.csq.study.springboot.sendmail;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class SendMailApplication {
	public static void main(String[] args) {
		SpringApplication.run(SendMailApplication.class, args);
	}
	
}

 

启动项目,分别访问:http://localhost:8088/sendMessage  、http://localhost:8088/sendOne 、http://localhost:8088/sendTwo、http://localhost:8088/sendThree

有如下截图:

发送短信验证码成功截图:

springboot集成发送邮件、短信的小测试demo_第2张图片

发送企业邮箱成功截图

springboot集成发送邮件、短信的小测试demo_第3张图片

发送qq邮箱成功截图:

springboot集成发送邮件、短信的小测试demo_第4张图片

 

发送163邮箱成功截图:

springboot集成发送邮件、短信的小测试demo_第5张图片

 

 说明:

发送短信我用的是 百度SMS短信通 我们可以进入官网:http://sms.webchinese.cn/  然后出注册、申请账号 ,做这一步就是为了那免费的五条短信啊(免费的都好用) ,获取到自己对应账号名称和密钥,后面需要用,然后就可以尝试发送短信了。本demo测试全部经过本人实际测试.有其它问题欢迎互相沟通。

 

 

 

 

 

你可能感兴趣的:(日常demo学习)