本地发送邮件没问题,部署在阿里云上邮件发送不出去,搜集整理后发现是阿里云禁用25端口导致。解决方法如下:
public static boolean sslSend(String content) throws AddressException, MessagingException, IOException{
MessageInfo msg1 = new MessageInfo(); msg1.setFrom("发件人邮箱"); msg1.setSendDate(new Date()); List<String> list = new ArrayList<>(); list.add("收件人邮箱"); msg1.setTo(list); msg1.setMsg("内容"); msg1.setSubject("主题"); EmailAccount emailAccount = new EmailAccount(); emailAccount.setUsername("邮箱名"); emailAccount.setPassword("密码"); emailAccount.setPlace("邮箱服务器"); 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", emailAccount.getPlace()); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true"); final String username = emailAccount.getUsername(); final String password = emailAccount.getPassword(); Session session = Session.getDefaultInstance(props, new Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }}); Message msg = new MimeMessage(session); // 设置发件人和收件人 msg.setFrom(new InternetAddress(emailAccount.getUsername())); List<String> tos = msg1.getTo(); Address to[] = new InternetAddress[tos.size()]; for(int i=0;i<tos.size();i++){ to[i] = new InternetAddress(tos.get(i)); } // 多个收件人地址 msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(msg1.getSubject()); // 标题 msg.setText(msg1.getMsg());// 内容 msg.setSentDate(new Date()); Transport.send(msg); System.out.println("EmailUtil ssl协议邮件发送打印" +msg.toString()); return true; }
static class EmailAccount{ // 邮箱用户 private String username; // 邮箱密码 private String password; // 邮箱服务器 private String place; public String getUsername() { return username; }
}
static class MessageInfo{ private String from; private List<String> to; private Date sendDate; private String subject; private String msg; public String getFrom() { return from; }}