1.登录163邮箱设置>>POP3/SMTP/IMAP>>开启SMTP服务
保存授权码
/**
* pom.xml
org.springframework.boot
spring-boot-starter-mail
*这边可以把host,username ,password 放到配置文件中,通过@Value("${spring.mail.host}")读取既可
*/
public static String host = "smtp.163.com"; //smtp服务主机
public static String username = "[email protected]"; //邮箱
public static String password = "xxxxxxxxxx"; //授权码
public static void main(String[] args) throws Exception {
String mesg="您的验证码:" + achieveCode() + ",如非本人操作,请忽略!请勿回复此邮箱";
SmallSnowflake.sendMail("[email protected]","测试",mesg);
System.out.println("邮件发送成功");
}
public static void sendMail(String to,String subject,String html) throws Exception {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost(host);
sender.setUsername(username);
sender.setPassword(password);
//编码集
sender.setDefaultEncoding("Utf-8");
MimeMessage mimeMessage = sender.createMimeMessage();
// 设置utf-8或GBK编码,否则邮件会有乱码
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
//发件人
messageHelper.setFrom(username, "测试");
//收件人
messageHelper.setTo(to);
//指定邮件标题
messageHelper.setSubject(subject);
//指定邮件内容
messageHelper.setText(html, true);
sender.send(mimeMessage);
}
// 随机验证码
public static String achieveCode() { //由于数字1 和0 和字母 O,l 有时分不清,所有,没有字母1 、0
String[] beforeShuffle= new String[] { "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z" };
StringBuffer sb = new StringBuffer();
Random rand=new Random();
for (int i = 0; i < 4; i++) {
sb.append(beforeShuffle[rand.nextInt(beforeShuffle.length)]); //随机获取4位
}
return sb.toString();
}
阿里云短信验证码
/**
*pom.xml
com.aliyun
aliyun-java-sdk-core
4.5.3
*/
public static void main(String[] args) throws Exception {
String phone = "12345678999"; //手机号
String code = achieveCode(); //验证码
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "XXXXXXXX", "XXXXXXXXXX");
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", phone);
request.putQueryParameter("SignName", "签名名称");
request.putQueryParameter("TemplateCode", "模板code");
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", code);
request.putQueryParameter("TemplateParam", jsonObject.toJSONString());
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
上面的代码可以拿到直接运行