最近做一個小項目要用到JAVA的郵箱的發送功能。遇到一些坑這里記錄分享一下:QQ群交流:697028234
1、QQ郵箱一定要設置開通SMTP/POP這項。並生成授權碼。
2、用MAVEN生成一個QUICKSTART項目,測試用的哈。加入依賴如下:
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
3、在main方法里加入如下代碼測試成功的哈。
package com.sendmail.sendmail_test; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * Hello world! * */ public class App { public static void main( String[] args ) throws MessagingException { // 配置發送郵件的環境屬性 final Properties props = new Properties(); /* * 可用的屬性: mail.store.protocol / mail.transport.protocol / mail.host / * mail.user / mail.from */ // 表示SMTP發送郵件,需要進行身份驗證 props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", "smtp.qq.com"); props.put("mail.transport.protocol", "smtp"); props.put("mail.debug", "true");
//遇到最多的坑就是下面這行,不加要報“A secure connection is requiered”錯。 props.put("mail.smtp.starttls.enable", "true"); // 發件人的賬號 props.put("mail.user", "XXXX@qq.com"); // 訪問SMTP服務時需要提供的密碼 props.put("mail.password", "這里是QQ郵箱授權碼"); // 構建授權信息,用於進行SMTP進行身份驗證 Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { // 用戶名、密碼 String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; // 使用環境屬性和授權信息,創建郵件會話 Session mailSession = Session.getInstance(props, authenticator); // 創建郵件消息 MimeMessage message = new MimeMessage(mailSession); // 設置發件人 InternetAddress form = new InternetAddress( props.getProperty("mail.user")); message.setFrom(form); // 設置收件人 InternetAddress to = new InternetAddress("3489417@qq.com"); message.setRecipient(RecipientType.TO, to); // 設置抄送,抄送和密送如果不寫正確的地址也要報錯。最好注釋不用。 // InternetAddress cc = new InternetAddress(""); // message.setRecipient(RecipientType.CC, cc); // // // 設置密送,其他的收件人不能看到密送的郵件地址 // InternetAddress bcc = new InternetAddress(""); // message.setRecipient(RecipientType.CC, bcc); // 設置郵件標題 message.setSubject("JAVA測試郵件"); // 設置郵件的內容體 message.setContent("<a href='http://www.XXX.org'>測試的郵件</a>", "text/html;charset=UTF-8"); // 發送郵件 Transport.send(message); } }