spring定时器结合项目发送邮件

pom.xml

com.sun.mail javax.mail 1.6.0

springMvc

xmlns:task=“http://www.springframework.org/schema/task”

http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd


工具类(util)

public class EmilUtil extends Authenticator {

public static String USERNAME = “[email protected]”;
public static String PASSWORD = “1.2.3.4.”;
public EmilUtil() {
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USERNAME, PASSWORD);
}

公共类(common)

public static String sendMail(String user,String pwd,String host,String from,String to,String subject,String content) throws Exception{
if (to != null) {
Properties props = System.getProperties();
props.put(“mail.smtp.host”, host);
props.put(“mail.smtp.auth”, “true”);
EmilUtil auth = new EmilUtil();
EmilUtil.USERNAME = user;
EmilUtil.PASSWORD = pwd;
Session session = Session.getInstance(props, auth);
session.setDebug(true);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
if (!to.trim().equals(""))
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to.trim()));
message.setSubject(subject);
MimeBodyPart mbp1 = new MimeBodyPart(); // 正文
mbp1.setContent(content, “text/html;charset=utf-8”);
Multipart mp = new MimeMultipart(); // 整个邮件:正文+附件
mp.addBodyPart(mbp1);
// mp.addBodyPart(mbp2);
message.setContent(mp);
message.setSentDate(new Date());
message.saveChanges();
Transport trans = session.getTransport(“smtp”);
trans.send(message);
System.out.println(message.toString());
} catch (Exception e) {
e.printStackTrace();
return “failure”;
}
return “success”;
} else {
return “failure”;
}
}

controller

@GetMapping(“queryGoodsList”)
@ResponseBody
@Scheduled(cron = “0/300 * * * * ?”)
public ServerResponse queryGoodsList(){
return goodsService.queryGoodsList();
}

service:

public ServerResponse queryGoodsList() {

QueryWrapper goodsQueryWrapper = new QueryWrapper<>();

goodsQueryWrapper.lt("stock",10);
//商品名,商品单价,商品现有库存
goodsQueryWrapper.select("productName","price","stock");
List goodsList = goodsMapper.selectList(goodsQueryWrapper);

String s = JSONObject.toJSONString(goodsList);
String user = "[email protected]";
String password = "yhwpqpuyqtiybhdd";
String host = "imap.qq.com";
String from = "[email protected]";
String to = "[email protected]";// 收件人
String subject = "花花";
//邮箱内容
StringBuffer sb = new StringBuffer();
String dataInfo = s;
sb.append(""+"
" + "
"+dataInfo+"

huahua

" +"
"); try { String res = SendMail.sendMail(user, password, host, from, to, subject, sb.toString()); System.out.println(res); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(s); return ServerResponse.success(s);

}

你可能感兴趣的:(spring)