最近公司要作一個郵箱註冊和重置密碼的功能,由於以前就作過,可是不是Springboot項目,因此相對來講仍是比較容易的,在這裏記錄一下。javascript
1、引用Maven依賴 這裏使用spring自帶的郵件jar包html
<!-- 郵件服務 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2、yml配置java
#郵箱配置
spring: mail: host: smtp.exmail.qq.com port: 465 protocol: smtp username: ******** //你的郵箱帳號 password: ******** //你的登錄密碼 default-encoding: UTF-8 properties: mail: smtp: auth: true starttls: enable: true required: true
3、建立EmailImpl類做爲email組件redis
@Component public class EmailImpl { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private RedisUtil redisUtil; @Value("${spring.mail.username}") public String from; @Value("${spring.mail.password}") public String password;// 登陸密碼 @Value("${spring.mail.protocol}") public String protocol;// 協議 @Value("${spring.mail.port}") public String port;// 端口 @Value("${spring.mail.host}") public String host;// 服務器地址 private String theme = "註冊驗證碼"; private String reset = "重置驗證碼"; //初始化參數 public Session initProperties() { Properties properties = new Properties(); properties.setProperty("mail.transport.protocol", protocol); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.port", port); // 使用smtp身份驗證 properties.put("mail.smtp.auth", "true"); // 使用SSL,企業郵箱必需 start // 開啓安全協議 MailSSLSocketFactory mailSSLSocketFactory = null; try { mailSSLSocketFactory = new MailSSLSocketFactory(); mailSSLSocketFactory.setTrustAllHosts(true); } catch (GeneralSecurityException e) { e.printStackTrace(); } properties.put("mail.smtp.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); properties.put("mail.smtp.socketFactory.port", port); Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); // 使用SSL,企業郵箱必需 end // TODO 顯示debug信息 正式環境註釋掉 session.setDebug(true); return session; } /** * 發送註冊郵箱驗證碼 * @param sender * @return */ public Boolean sendHtmlEmail(String sender) { boolean lean = false; try { Session session = initProperties(); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(from,"Tesra"));// 發件人,能夠設置發件人的別名 // 收件人,多人接收 InternetAddress[] internetAddressTo = new InternetAddress().parse(sender); mimeMessage.setRecipients(Message.RecipientType.TO, internetAddressTo); // 主題 mimeMessage.setSubject(theme); // 時間 mimeMessage.setSentDate(new Date()); // 容器類 附件 MimeMultipart mimeMultipart = new MimeMultipart(); // 能夠包裝文本,圖片,附件 MimeBodyPart bodyPart = new MimeBodyPart(); String code = CodeUtils.getMathVal(); // 設置內容 getEmailHtml是郵箱內容模板 bodyPart.setContent(getEmailHtml(sender,code), "text/html; charset=UTF-8"); mimeMultipart.addBodyPart(bodyPart); // 添加圖片&附件 // bodyPart = new MimeBodyPart(); // bodyPart.attachFile(fileSrc); // mimeMultipart.addBodyPart(bodyPart); mimeMessage.setContent(mimeMultipart); mimeMessage.saveChanges(); Transport.send(mimeMessage); redisUtil.set(sender,code, UserConstant.time); lean = true; } catch (MessagingException e) { e.printStackTrace(); lean = false; logger.error("發送註冊郵件失敗:"+sender+" ----"+e.getMessage()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); lean = false; logger.error("發送註冊郵件失敗:"+sender+" ----"+e.getMessage()); } return lean; } /** * 發送重置郵箱驗證碼 * @param sender * @return */ public Boolean sendHtmlEmailCZ(String sender) { Boolean lean = false; try { Session session = initProperties(); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(from,"Tesra"));// 發件人,能夠設置發件人的別名 // 收件人,多人接收 InternetAddress[] internetAddressTo = new InternetAddress().parse(sender); mimeMessage.setRecipients(Message.RecipientType.TO, internetAddressTo); // 主題 mimeMessage.setSubject(reset); // 時間 mimeMessage.setSentDate(new Date()); // 容器類 附件 MimeMultipart mimeMultipart = new MimeMultipart(); // 能夠包裝文本,圖片,附件 MimeBodyPart bodyPart = new MimeBodyPart(); String code = CodeUtils.getMathVal(); // 設置內容 getEmailReset是發送郵箱的html模板 bodyPart.setContent(getEmailReset(sender,code), "text/html; charset=UTF-8"); mimeMultipart.addBodyPart(bodyPart); // 添加圖片&附件 // bodyPart = new MimeBodyPart(); // bodyPart.attachFile(fileSrc); // mimeMultipart.addBodyPart(bodyPart); mimeMessage.setContent(mimeMultipart); mimeMessage.saveChanges(); Transport.send(mimeMessage); redisUtil.set(sender,code, UserConstant.time); lean = true; } catch (MessagingException e) { e.printStackTrace(); lean = false; logger.error("發送重置郵件失敗:"+sender+" ----"+e.getMessage()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); lean = false; logger.error("發送重置郵件失敗:"+sender+" ----"+e.getMessage()); } return lean; } }
4、郵箱html模板spring
/** * 註冊郵箱模板 * @param to 郵箱號 * @param code 驗證碼 * @return */ public String getEmailHtml(String to,String code){ String[] tos = to.split("@"); String sub = tos[0].substring(0,2); String email = sub+"*******@"+tos[1]; String html = "<div style=\"padding: 0px 0px 0px 20px;box-sizing: border-box;color: #333333;font-family: \"microsoft yahei\";font-size: 14px\">" + "<h3 style=\"font-weight: normal;font-size: 18px;\">Test測試</h3>" + "<h4 style=\"color:#2672EC;font-size: 40px;margin-top: 24px;font-weight: normal;\">帳號註冊驗證碼</h4>" + "<div style=\"margin-top: 40px;\">您好,您正在使用<a href=\"javascript:;\" target=\"_blank\" style=\"color: #2672EC;text-decoration: none;\">"+email+"</a>註冊帳號。</div>" + "<div style=\"margin-top: 30px;\">您的註冊驗證碼爲:<em style=\"font-style: normal;font-weight: 600;\">"+code+"</em></div>" + "<div style=\"margin-top: 35px;\">謝謝!</div>" + "<div style=\"margin-top: 10px;\">Test測試</div>" + "</div>"; return html; }
5、方法調用安全
@Autowired private EmailImpl emailImpl; //email郵箱號 emailImpl.sendHtmlEmail(email);
至此就完成了SpringBoot使用qq郵箱發送郵件。服務器