发送邮件代码
1 public static void sendMailByGmail(String subject, String text, String... toEmail) throws Exception{ 2 final String host = "smtp.gmail.com";//邮件服务器 3 final String from = "xxx@gmail.com";//发件人的邮箱 4 final String pass = "*******";//发件人密码 5 final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 6 7 // Get a Properties object 8 Properties props = System.getProperties(); 9 props.setProperty("mail.smtp.host", host); 10 props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); 11 props.setProperty("mail.smtp.socketFactory.fallback", "false"); 12 props.setProperty("mail.smtp.localhost", "127.0.0.1"); 13 props.setProperty("mail.smtp.port", "465"); 14 props.setProperty("mail.smtp.socketFactory.port", "465"); 15 props.put("mail.smtp.auth", "true"); 16 17 Session session = Session.getDefaultInstance(props, null); 18 MimeMessage message = new MimeMessage(session); 19 message.setFrom(new InternetAddress(from)); 20 21 InternetAddress[] toAddress = new InternetAddress[toEmail.length]; 22 23 // 批量发送邮件 24 for( int i=0; i < toEmail.length; i++ ) { 25 toAddress[i] = new InternetAddress(toEmail[i]); 26 } 27 System.out.println(Message.RecipientType.TO); 28 29 for( int i=0; i < toAddress.length; i++) { 30 message.addRecipient(Message.RecipientType.TO, toAddress[i]); 31 } 32 message.setSubject(subject); 33 message.setText(text); 34 Transport transport = session.getTransport("smtp"); 35 transport.connect(host, from, pass); 36 transport.sendMessage(message, message.getAllRecipients()); 37 transport.close(); 38 }
//遇到的问题
该问题就是在国内无法连接,要使用国外的服务器
使用国外的服务器之后,还会报错
javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted
就要进行下图的设置
然后还有服务器的端口开放 出入方向都设置一下