基于QQ服务器JavaMail邮箱SSL密码第三方发送邮件
网上javaMail邮箱推送代码太多,大都是有缺陷的,今天做项目刚好要用到,于是发了大半天的时间解决的这个问题。
jar包:javax.mail.jar
代码:
1 import java.io.IOException; 2 import java.security.GeneralSecurityException; 3 import java.util.Date; 4 import java.util.Properties; 5 6 import javax.mail.Message.RecipientType; 7 import javax.mail.Authenticator; 8 import javax.mail.Message; 9 import javax.mail.MessagingException; 10 import javax.mail.NoSuchProviderException; 11 import javax.mail.PasswordAuthentication; 12 import javax.mail.Session; 13 import javax.mail.Transport; 14 import javax.mail.internet.AddressException; 15 import javax.mail.internet.InternetAddress; 16 import javax.mail.internet.MimeMessage; 17 18 19 20 public class EmailPushUtil { 21 public static void main(String[] args) { 22 boolean isSSL = true; 23 String host = "smtp.qq.com"; 24 int port = 465; 25 String from = " ";//发送者邮箱 26 String to = " ";//接收者邮箱 27 boolean isAuth = true; 28 final String username = " ";//发送者账号 29 final String password = " ";//密码 30 31 Properties props = new Properties(); 32 props.put("mail.smtp.ssl.enable", isSSL); 33 props.put("mail.smtp.host", host); 34 props.put("mail.smtp.port", port); 35 props.put("mail.smtp.auth", isAuth); 36 37 Session session = Session.getDefaultInstance(props, new Authenticator() { 38 @Override 39 protected PasswordAuthentication getPasswordAuthentication() { 40 return new PasswordAuthentication(username, password); 41 } 42 }); 43 44 try { 45 Message message = new MimeMessage(session); 46 47 message.setFrom(new InternetAddress(from)); 48 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 49 message.setSubject("主题"); 50 message.setText("内容"); 51 52 Transport.send(message); 53 } catch (AddressException e) { 54 e.printStackTrace(); 55 } catch (MessagingException e) { 56 e.printStackTrace(); 57 } 58 59 System.out.println("发送完毕!"); 60 } 61 }