Java發(fā)送qq郵件(方式2)
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
? ? /**
? ? * 發(fā)送qq郵件(方式2)
? ? *
? ? * @param sender? ? 發(fā)送方郵箱
? ? * @param senderName 發(fā)送方姓名
? ? * @param authCode? 授權(quán)碼
? ? * @param receiver? 接受方郵箱
? ? * @param subject? ? 主題
? ? * @param content? ? 內(nèi)容(可使用HTML標(biāo)簽)
? ? *? ? ? ? ? ? ? ? ? 需導(dǎo)入依賴
? ? *? ? ? ? ? ? ? ? ? <dependency>
? ? *? ? ? ? ? ? ? ? ? <groupId>org.apache.commons</groupId>
? ? *? ? ? ? ? ? ? ? ? <artifactId>commons-email</artifactId>
? ? *? ? ? ? ? ? ? ? ? </dependency>
? ? */
? ? public static void sendMail(String sender, String senderName, String authCode,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? String receiver, String subject, String content) throws Exception {
? ? ? ? // 設(shè)置Session鏈接屬性
? ? ? ? Properties props = new Properties();
? ? ? ? // 設(shè)置SMTP發(fā)送服務(wù)器
? ? ? ? props.setProperty("mail.transport.protocol", "SMTP");
? ? ? ? props.setProperty("mail.host", "smtp.qq.com");
? ? ? ? // 設(shè)置驗證
? ? ? ? props.setProperty("mail.smtp.auth", "true");
? ? ? ? // 創(chuàng)建驗證器
? ? ? ? Authenticator auth = new Authenticator() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public PasswordAuthentication getPasswordAuthentication() {
? ? ? ? ? ? ? ? // 設(shè)置用戶名與授權(quán)碼
? ? ? ? ? ? ? ? return new PasswordAuthentication(sender, authCode);
? ? ? ? ? ? }
? ? ? ? };
? ? ? ? // 創(chuàng)建 Session郵件服務(wù)器會話對象 Session
? ? ? ? Session session = Session.getInstance(props, auth);
? ? ? ? // 創(chuàng)建一個Message簇捍,它相當(dāng)于是郵件內(nèi)容
? ? ? ? Message message = new MimeMessage(session);
? ? ? ? // 設(shè)置發(fā)送者與姓名
? ? ? ? message.setFrom(new InternetAddress(sender, senderName));
? ? ? ? // 設(shè)置發(fā)送方式與接收者
? ? ? ? message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
? ? ? ? // 設(shè)置標(biāo)題與內(nèi)容
? ? ? ? message.setSubject(subject);
? ? ? ? message.setContent(content, "text/html;charset=utf-8");
? ? ? ? // 創(chuàng)建 Transport用于將郵件發(fā)送
? ? ? ? Transport.send(message);
? ? }
獲取郵箱授權(quán)碼教程
qq郵箱:[https://baijiahao.baidu.com/s?id=1552315463915496&wfr=spider&for=pc](https://baijiahao.baidu.com/s?id=1552315463915496&wfr=spider&for=pc)
更多方法訪問Java工具網(wǎng)[utils.net.cn](http://utils.net.cn/)
每個方法單獨使用凛剥,不互相依賴,持續(xù)更新蓝撇!