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

最近本身折騰了下Java中利用mai發送QQ郵件html

1.QQ郵箱設置session

  1.1 進去QQ郵箱-->設置-->帳號-->進行設置以下圖ide

  

2.foxmail設置(因爲我要利用它收郵件)this

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

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

3.Java中代碼配置3d

  3.1 發送郵件配置代碼code

//發送郵箱驗證
        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輔助類htm

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
相關文章
相關標籤/搜索