java mail使用qq郵箱發郵件的配置方法


最近自己折騰了下Java中利用mai發送QQ郵件

1.QQ郵箱設置

  1.1 進去QQ郵箱-->設置-->賬號-->進行設置如下圖

  

2.foxmail設置(由於我要利用它收郵件)

  2.1 參照官方的設置即可 http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=371

  ps:填寫的郵箱密碼是獨立密碼:需要注意的就是SSL鏈接要勾選;smtp端口是465

3.Java中代碼配置

  3.1 發送郵件配置代碼

//發送郵箱驗證
        try {
            Properties prop = new Properties();
            prop.setProperty("mail.transport.protocol", "smtp");
            prop.setProperty("mail.smtp.host", "smtp.qq.com");
            prop.setProperty("mail.smtp.auth", "true");
            prop.put("mail.smtp.port","25");
            prop.setProperty("mail.debug", "true");
            Authenticator authenticator = new PopAuthenticator("1274444444@qq.com", "4444444");
            //創建會話
            Session session = Session.getInstance(prop,authenticator);
            //填寫信封寫信
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("1271099894@qq.com"));
            msg.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));
            msg.setSubject(user.getUsername()+"激活郵箱!");
            msg.setText(user.getUsername()+",你好請到這個地址激活你的賬號:http://www.estore.com/ActiveServlet?activecode="+user.getActivecode());
            //驗證用戶名密碼發送郵件
            Transport transport = session.getTransport();
//transport.connect("1274444444@qq.com","4444444");
            transport.send(msg);
        } 
        
View Code

  3.2輔助類

public class PopAuthenticator extends Authenticator {
     String userName = null;
        String password = null;
        public PopAuthenticator() {
        }
        public PopAuthenticator(String username, String password) {
            this.userName = username;
            this.password = password;
        }
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
}
View Code

  3.3 如果要發送html可以參考如下代碼:

MimeMessage mailMessage = new MimeMessage(sendMailSession);
        mailMessage.setFrom(new InternetAddress("1219999@qq.com"));
        // Message.RecipientType.TO屬性表示接收者的類型為TO
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        mailMessage.setSubject(subject, "UTF-8");
        mailMessage.setSentDate(new Date());
        // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
        Multipart mainPart = new MimeMultipart();
        // 創建一個包含HTML內容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        html.setContent(content.trim(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);
        Transport.send(mailMessage);
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM