在項(xiàng)目中,常常使用某一個(gè)郵箱地址作為項(xiàng)目對(duì)外的公共發(fā)送郵件的地址,QQ郵箱被使用的概率不大,但是QQ郵箱的配置使用卻別其他郵箱較為復(fù)雜,下面做一個(gè)簡(jiǎn)單的demo來演示如何配置并使用QQ郵箱發(fā)送郵件
1.為QQ郵箱開通POP3/SMTP服務(wù)

2.開啟的時(shí)候需要使用你注冊(cè)的手機(jī)號(hào)向騰訊發(fā)送一個(gè)短信(按照上面提示發(fā)送),發(fā)送成功之后點(diǎn)擊“我已發(fā)送”

3.驗(yàn)證成功之后,QQ會(huì)返回一個(gè)授權(quán)碼

4.在項(xiàng)目中引入javamail相關(guān)jar包
? ? demo中使用的是javax.mail-1.5.1.jar版本
5.java代碼如下:
public class MailUtils2 {
? ? ? ? private static String smtp_host ="smtp.qq.com"; // QQ SMTP服務(wù)
? ? ? ? private static String username = "使用發(fā)件人郵箱地址"; // 郵箱賬戶
? ? ? ? private static String password = "iiotqaasiaiabfgc"; // 郵箱授權(quán)碼-該授權(quán)碼就是在開啟QQPOP3/SMTP服務(wù)時(shí)返回的那串激活碼
? ? ? ? private static String from = "使用發(fā)件人郵箱地址"; // 郵箱賬戶
? ? ? ? public static void sendMail(String subject, String content, String to) {
? ? ? ? ? ? ? ? //設(shè)置發(fā)送郵件的properties
? ? ? ? ? ? ? ? Properties props = new Properties();
? ? ? ? ? ? ? ? props.setProperty("mail.smtp.host", smtp_host);
? ? ? ? ? ? ? ? props.setProperty("mail.transport.protocol", "smtp");
? ? ? ? ? ? ? ? props.setProperty("mail.smtp.auth", "true");
//? ? ? ? ? ? ? ? QQ 郵箱需要 SSL 加密
? ? ? ? ? ? ? ? props.setProperty("mail.smtp.auth", "true");
? ? ? ? ? ? ? ? props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
? ? ? ? ? ? ? ? props.setProperty("mail.smtp.port", "465");
? ? ? ? ? ? ? ? props.setProperty("mail.smtp.socketFactory.port", "465");
? ? ? ? ? ? ? ? //準(zhǔn)備連接對(duì)象
? ? ? ? ? ? ? ? Session session = Session.getInstance(props);
? ? ? ? ? ? ? ? //創(chuàng)建郵件信息
? ? ? ? ? ? ? ? Message message = new MimeMessage(session);
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? ? ? message.setFrom(new InternetAddress(from));//設(shè)置發(fā)件人
? ? ? ? ? ? ? ? ? ? ? ? message.setRecipient(RecipientType.TO, new InternetAddress(to));//設(shè)置收件人以及收件人地址
? ? ? ? ? ? ? ? ? ? ? ? message.setSubject(subject);//郵件主題
? ? ? ? ? ? ? ? ? ? ? ? message.setContent(content, "text/html;charset=utf-8");//支持富文本內(nèi)容
? ? ? ? ? ? ? ? ? ? ? ? Transport transport = session.getTransport();
? ? ? ? ? ? ? ? ? ? ? ? transport.connect(smtp_host, username, password);
? ? ? ? ? ? ? ? ? ? ? ? transport.sendMessage(message, message.getAllRecipients());//發(fā)送郵件
? ? ? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? ? ? ? ? throw new RuntimeException("郵件發(fā)送失敗...");
? ? ? ? ? ? ? ? }
? ? ? ? }
? ? ? ? public static void main(String[] args) {
? ? ? ? ? ? ? ? //測(cè)試
? ? ? ? ? ? ? ? sendMail("測(cè)試郵件", "你好a", "收件人郵箱地址");
? ? ? ? }
}
5.郵箱可以正常收到
