package org.zhiyi.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
import java.util.regex.Pattern;
@Component
public class Email {
@Value("${email.stmp}")
String stmp;
@Value("${email.account}")
String username;
@Value("${email.pwd}")
String password;
Session session;
private void createSession() {
Properties prop = new Properties();
prop.setProperty("mail.host","smtp.qq.com");
prop.setProperty("mail.transport.protocol","smtp");
prop.setProperty("mail.smtp.auth","true");
session = Session.getInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
}
//发送邮件
public void send(String recipient, String subject, String content) throws MessagingException {
createSession();
if(!emailFormat(recipient)){
throw new RuntimeException("email format error!");
}
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(username));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
msg.setSubject(subject, "utf-8");
MimeBodyPart body = new MimeBodyPart();
body.setContent(content, "text/html;charset=utf-8");
MimeMultipart mul = new MimeMultipart();
mul.addBodyPart(body);
msg.setContent(mul);
Transport.send(msg);
}
//邮件模板
public String mesTemplate(String title, String body) {
StringBuilder sb = new StringBuilder();
sb.append("<h1>" + title + "</h1>");
sb.append("<div>" + body + "</div>");
return sb.toString();
}
//验证邮箱格式
final static Pattern partern = Pattern.compile("[a-zA-Z0-9]+[\\.]{0,1}[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z]+");
public static boolean emailFormat(String email){
return partern.matcher(email).matches();
}
}
Email email = new Email();
String code = "1234";
email.send("1098628245@qq.com", "验证码", email.mesTemplate("验证码", "您的验证码为<h2>" + code + "</h2>,验证码有效期为五分钟!"));