1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| package com.autohome.common.email;
import javax.mail.Address; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties;
public class MailUtil { private static final String emailAddr = "xxx@qq.com"; private static final String authCode = "xxx";
public static void sendMail(String to, String code) { Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.qq.com"); props.setProperty("mail.smtp.auth", "true"); Session session = Session.getInstance(props);
Message message = new MimeMessage(session); try { Address fromAddr = new InternetAddress(emailAddr); message.setFrom(fromAddr);
Address toAddr = new InternetAddress(to); message.setRecipient(MimeMessage.RecipientType.TO, toAddr);
message.setSubject("来自 " + emailAddr + " 的安全验证码"); message.setContent("这里是邮件的正文信息\n\n您的验证码为:" + code, "text/html;charset=UTF-8");
Transport transport = session.getTransport("smtp"); transport.connect("smtp.qq.com", emailAddr, authCode); transport.sendMessage(message, message.getAllRecipients());
} catch (Exception e) { e.printStackTrace(); } }
public static String generateRandomCode(int length) { String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; StringBuilder sb = new StringBuilder(); while (sb.length() < length) { int index = (new java.util.Random()).nextInt(s.length()); Character ch = s.charAt(index); if (sb.indexOf(ch.toString()) < 0) { sb.append(ch); } } return sb.toString(); } }
|