springboot java代码实现邮件通知

通过代码实现发送邮件通知到相关负责人,实现模板群发或单对单发送 ,本文旨在实现功能,所以创建文件顺序有些不认真

 

包结构:

springboot java代码实现邮件通知_第1张图片

1:首先创建一个config类 MailConfig 



import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.springframework.stereotype.Component;

/** 
 * 邮件读取配置类
 * @author 
 * 

2019年5月9日 上午11:13:51

* @see * @version 1.0 */ @Component public class MailConfig { private static final String PROPERTIES_DEFAULT = "mailConfig.properties"; public static String host; public static Integer port; public static String userName; public static String passWord; public static String emailForm; public static String timeout; public static String personal; public static Properties properties; static{ init(); } /** * 初始化 */ private static void init() { properties = new Properties(); try{ InputStream inputStream = MailConfig.class.getClassLoader().getResourceAsStream(PROPERTIES_DEFAULT); properties.load(inputStream); inputStream.close(); host = properties.getProperty("mailHost"); port = Integer.parseInt(properties.getProperty("mailPort")); userName = properties.getProperty("mailUsername"); passWord = properties.getProperty("mailPassword"); emailForm = properties.getProperty("mailUsername"); timeout = properties.getProperty("mailTimeout"); //发送人 personal = properties.getProperty("mailSender"); } catch(IOException e){ e.printStackTrace(); } } }

 

2: 需要写一个配置类 mailConfig.properties

里面的*号替换成自己的信息

mailConfig.properties
#服务器
mailHost=smtp.163.com
#端口号
mailPort=25
#邮箱账号(使用者改成自己的)
mailUsername=*****@163.com
#邮箱密码(使用者改成自己的)
mailPassword=*****
#时间延迟
mailTimeout=25000
# 邮件发送人信息
mailSender = ******

 

3:创建一个实体对象传参 MailEntity  (本文按要求写成了一个小项目,不需要的直接传参也可以)



import java.io.Serializable;

/** 
 * 邮件对象
 * @author 
 * 

2019年5月9日 下午5:32:04

* @see * @version 1.0 */ public class MailEntity implements Serializable{ /** * {用一句话描述这个变量表示什么} */ private static final long serialVersionUID = 4542302475678065294L; /*多个邮箱可用 private String [] users;*/ private String users; private String title; private String content; public String getUsers() { return users; } public void setUsers(String users) { this.users = users; } 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; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((content == null) ? 0 : content.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); result = prime * result + ((users == null) ? 0 : users.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj){ return true; } if (obj == null){ return false; } if (getClass() != obj.getClass()){ return false; } MailEntity other = (MailEntity) obj; if (content == null) { if (other.content != null){ return false; } } else if (!content.equals(other.content)){ return false; } if (title == null) { if (other.title != null){ return false; } } else if (!title.equals(other.title)){ return false; } if (users == null) { if (other.users != null){ return false; } } else if (!users.equals(other.users)){ return false; } return true; } @Override public String toString() { return "MailEntity [users=" + users + ", title=" + title + ", content=" + content + "]"; } }

 

4:将配置使用起来,创建一个util工具   MailUtil  (这里的to  多个地址用String[] 接收)



import java.io.UnsupportedEncodingException;
import java.util.Properties;

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

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.mozi.dap.mail.config.MailConfig;

public class MailUtil {
	private static final String HOST = MailConfig.host;
	private static final Integer PORT = MailConfig.port;
	private static final String USERNAME = MailConfig.userName;
	private static final String PASSWORD = MailConfig.passWord;
	private static final String EMAILFORM = MailConfig.emailForm;
	private static final String TIMEOUT = MailConfig.timeout;
	private static final String PERSONAL = MailConfig.personal;
	private static JavaMailSenderImpl mailSender = createMailSender();

	/**
	 * 邮件发送器
	 *
	 * @return 配置好的工具
	 */
	private static JavaMailSenderImpl createMailSender() {
		JavaMailSenderImpl sender = new JavaMailSenderImpl();
		sender.setHost(HOST);
		sender.setPort(PORT);
		sender.setUsername(USERNAME);
		sender.setPassword(PASSWORD);
		sender.setDefaultEncoding("Utf-8");
		Properties p = new Properties();
		p.setProperty("mail.smtp.timeout", TIMEOUT);
		p.setProperty("mail.smtp.auth", "false");
		sender.setJavaMailProperties(p);
		return sender;
	}

	/**
  * 发送邮件
  *
  * @param to 接受人   多个邮箱  String[] to  单个String to
  * @param subject 主题
  * @param html 发送内容
  * @throws MessagingException 异常
  * @throws UnsupportedEncodingException 异常
  */
	 public static void sendMail(String to, String subject, String html) throws MessagingException,UnsupportedEncodingException {
	     MimeMessage mimeMessage = mailSender.createMimeMessage();
	     // 设置utf-8或GBK编码,否则邮件会有乱码
	     MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
	     messageHelper.setFrom(EMAILFORM, PERSONAL);
	     messageHelper.setTo(to);
	     messageHelper.setSubject(subject);
	     messageHelper.setText(html, true);
	     mailSender.send(mimeMessage);
	 }
}

 5:写个控制层接口用来触发... MailController   (这里参数用@RequestBody接收是由于我其他项目调用,不需要的自己调整,不影响功能)



import java.io.UnsupportedEncodingException;

import javax.mail.MessagingException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mozi.dap.mail.entity.MailEntity;
import com.mozi.dap.mail.util.MailUtil;

/** 
 * 邮件发送控制层
 * @author 
 * 

2019年5月9日 下午1:47:25

* @see * @version 1.0 */ @Controller @RequestMapping("mail/v1.0") public class MailController { /** * 邮件发送 * @param users 接受邮箱,可多个 * @param title 标题 * @param content 邮件内容 */ @RequestMapping(value="/sendMail",method = RequestMethod.POST) @ResponseBody public void sendMail( @RequestBody MailEntity mailEntity){ try { MailUtil.sendMail(mailEntity.getUsers(), mailEntity.getTitle(), mailEntity.getContent()); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }

 

6:想要使用上述的内容,还需要关键的jar包依赖,我换了好几个,目前使用的是以下俩个jar依赖,第一个应该大家都没有问题,私服里通常都有,第二个没有的话自己下载一个吧,2.1.3  或2.1.6都没问题,如果还有Impl引入报错,我查到的问题是jar冲突或者是springframework里的哪个东西是父级依赖,那么参考下面我自己用的pom吧,自己调整,不要笑,不要恼,本人小白怕误导。

        
            org.springframework.boot
            spring-boot-starter-mail
        

        
            com.sun.mail
            javax.mail
        

 ps:还有问题请看这里



    4.0.0
    jar
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.3.RELEASE
         
    
    com.mozi.dap
    dap-mailservice
    0.0.1
    dap-mailservice
    Demo project for Spring Boot

    
        1.8
    

    

        
            org.springframework.boot
            spring-boot-starter-freemarker
        

        
            org.springframework.boot
            spring-boot-starter-web
            
                
                    org.springframework.boot
                    spring-boot-starter-tomcat
                
            
        
        
            org.springframework.boot
            spring-boot-starter-tomcat
            provided
        
        
            org.springframework.boot
            spring-boot-starter-mail
        
        
            org.springframework.boot
            spring-boot-starter-validation
        
        
            com.sun.mail
            javax.mail
        
    
    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.8
                    1.8
                    UTF-8
                
            
        
    

7:调用路径后邮件接收结果 (邮件内容我是在另一个服务直接拼接的,如需使用定义格式,内容赋值时,内容中拼接html标签)

springboot java代码实现邮件通知_第2张图片

以上内容可以自己改造,希望对大家有所帮助 

你可能感兴趣的:(java,开发技术,笔记)