阿里云服务器发送邮件失败,25端口被禁用,采用ssl 方式 465端口发送


/**
 *  邮件工具类
 * User: NZG
 * Date: 2019/3/8
 * Time: 12:25
 **/
@Data
@Component
@Configuration
@ConfigurationProperties(prefix = "email")
//@PropertySource("classpath:config/application.properties")
public class EmailConfig {

    private String myEmailAccount;  // 发件人 账号

    private String myEmailPassword; //密码,是你自己的设置的授权码

    private String email163SmtpHost;   // SMTP服务器(这里用的163 SMTP服务器)

    private String smtp163Port;// 端口号,这个是163使用到的;QQ的应该是465或者875

}


# 邮件发送 (网易)
email.myEmailAccount=17719@163.com
email.myEmailPassword=ng87187  
email.email163SmtpHost=smtp.163.com 
email.smtp163Port=25  

   

 @Autowired
 private EmailConfig emailConfig;
public ResponseResult<String> sendEmail(SendEmailCodeReqVO vo) {
try {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = new Properties();
props.setProperty("mail.smtp.host", emailConfig.getEmail163SmtpHost());
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", emailConfig.getSmtp163Port());
props.setProperty("mail.smtp.socketFactory.port", emailConfig.getSmtp163Port());
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailConfig.getMyEmailAccount(),
emailConfig.getMyEmailPassword());
}});

session.setDebug(true);
MimeMessage message = new MimeMessage(session);
// 收件人
message.setRecipients(Message.RecipientType.TO, vo.getReceiveEmailAccount());
// 发件人
message.setFrom(new InternetAddress(emailConfig.getMyEmailAccount()));
//短信发送类型
Integer type = vo.getType();
EmailSendType sms = EmailSendType.getSmsEnumByType(type);
// 内容(这个内容还不能乱写,有可能会被SMTP拒绝掉;多试几次吧)
String msg = "";
String pwd = PassWordUtils.editPassword();
switch (sms) {
case FORGET_PWD:
msg = MessageFormat.format(PatientConstants.EMAIL_MESSAGE_PROMPT, pwd);
break;
default:
break;
}
message.setSubject("辅助系统随机密码");
message.setContent(msg, "text/html;charset=UTF-8");
message.setSentDate(new Date());
message.saveChanges();
Transport.send(message);
//根据邮箱修改密码
UserPraient user = userHandler.getUserByEmail(vo.getReceiveEmailAccount());
if(user==null){
return ResponseResult.failNotice(PatientSystemCode.USER_REG_REEOR.msg());
}
user.setUserPassword(PassWordUtils.entryptPassword(pwd));
userHandler.editUserPassword(user);
} catch (MessagingException e) {
e.printStackTrace();
return ResponseResult.failNotice(PatientSystemCode.MAIL_DELIVERY_FAILED.msg());
}
return ResponseResult.success();
}
原文地址:https://www.cnblogs.com/EveningWind/p/10510224.html