上次写的java发送邮件的方法并不完善,这次写了个比较完善的接口,方便使用的时候调用,后期我还会继续完善
 
引入Maven
1 2 3 4 5
   | <dependency> 	<groupId>javax.mail</groupId> 	<artifactId>mail</artifactId> 	<version>1.5.0-b01</version> </dependency>
   | 
 
代码
邮箱账号这里还以搜狐邮箱为例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
   | package com.lzc.mail.utlis;
  import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.UnsupportedEncodingException; import java.util.Properties;
 
 
 
 
 
 
 
 
  public class MailUtli {          private final static String userName = "xxxx@sohu.com";          private final static String password = "xxxxxxxxxxx";          private final static String host = "smtp.sohu.com";          private final static String port = "465";
           private final static String name = "小李同志";     private static final Properties properties = new Properties();
      static {                  properties.put("mail.smtp.host", host);                  properties.put("mail.smtp.port", port);                  properties.put("mail.smtp.auth", true);         properties.put("mail.smtp.ssl.enable", "true");         properties.put("mail.smtp.ssl.protocols", "TLSv1.2");
      }
 
      
 
 
 
 
 
      public static void sendAMessage(String to, String subject, String body) {                  Session session = Session.getInstance(properties, new javax.mail.Authenticator() {             protected javax.mail.PasswordAuthentication getPasswordAuthentication() {                                  return new javax.mail.PasswordAuthentication(userName, password);             }         });                           Message message = new MimeMessage(session);         try {                          InternetAddress internetAddress = new InternetAddress(userName, name);             message.setFrom(internetAddress);
                                        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));                          message.setSubject(subject);                          message.setText(body);
                           Transport.send(message);         } catch (UnsupportedEncodingException | MessagingException e) {             throw new RuntimeException(e);         }     } }
 
   |