1.问题描述
- 通过java程序实现邮箱发送验证码的功能
- 使用一段时间后出现发送邮件失败的问题
- 排查后提示:javax.mail.AuthenticationFailedException: 535 Error: authentication failed, syste
- 完整日志
DEBUG: setDebug: JavaMail version 1.4.7
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.exmail.qq.com", port 465, isSSL true
220 smtp.qq.com Esmtp QQ QMail Server
DEBUG SMTP: connected to host "smtp.exmail.qq.com", port: 465EHLO DESKTOP-KFLLPQC
250-smtp.qq.com
250-PIPELINING
250-SIZE 73400320
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN
250-MAILCOMPRESS
250 8BITMIME
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "73400320"
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN"
DEBUG SMTP: Found extension "AUTH=LOGIN", arg ""
DEBUG SMTP: Found extension "MAILCOMPRESS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN failed
备注:从日志可以看出是登录授权失败问题。
2.问题解决
- 邮箱的密码需要修改为绑定的微信客户端专用密码
// 配置企业邮箱的基础信息,并发送邮件public boolean sendMailQq(String email,String title, String emailMsg) {Properties prop = new Properties();//协议prop.setProperty("mail.transport.protocol", "smtp");//服务器prop.setProperty("mail.smtp.host", "smtp.exmail.qq.com");//端口prop.setProperty("mail.smtp.port", "465");//使用smtp身份验证prop.setProperty("mail.smtp.auth", "true");//使用SSL,企业邮箱必需!//开启安全协议MailSSLSocketFactory sf = null;try {sf = new MailSSLSocketFactory();sf.setTrustAllHosts(true);} catch (GeneralSecurityException e1) {e1.printStackTrace();}prop.put("mail.smtp.ssl.enable", "true");prop.put("mail.smtp.ssl.socketFactory", sf);// 获取Session对象// 需要生成邮箱绑定的微信客户端专用密码,邮箱本身的密码会登陆失败Session s = Session.getDefaultInstance(prop,new Authenticator() {//此访求返回用户和密码的对象@Overrideprotected PasswordAuthentication getPasswordAuthentication() {PasswordAuthentication pa = new PasswordAuthentication("你的邮箱", "你的邮箱绑定的微信客户端专用密码");return pa;}});//设置session的调试模式,发布时取消s.setDebug(true);MimeMessage mimeMessage = new MimeMessage(s);try {mimeMessage.setFrom(new InternetAddress("case_team_work@cgr.com.cn","case_team_work@cgr.com.cn"));mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(email));//设置主题mimeMessage.setSubject(title);mimeMessage.setSentDate(new Date());//设置内容mimeMessage.setText(emailMsg);mimeMessage.saveChanges();//发送Transport.send(mimeMessage);return true;} catch (MessagingException | UnsupportedEncodingException e) {throw new ServiceException(ExceptionEnum.EMAIL_VERIFICATION_CODE_SEND_FAILED);}}