導包
<!– 發送郵件 –> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.0</version> </dependency> </dependencies> qq郵箱開啟POP3/SMTP服務
設置-.>賬戶->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務
開啟POP3/SMTP服務
生成授權碼后將授權碼保存,后面會用
代碼
package com.spring.until; import java.security.GeneralSecurityException; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; 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; import com.sun.mail.util.MailSSLSocketFactory; public class SendEmail { public static boolean send(String email,String title,String body) throws GeneralSecurityException { // 收件人電子郵箱 String to = email; // 發件人電子郵箱 String from = PropertiesUntil.Properties(“account”); // 指定發送郵件的主機為 smtp.qq.com String host = “smtp.qq.com”; //QQ 郵件服務器 // 獲取系統屬性 Properties properties = System.getProperties(); // 設置郵件服務器 properties.setProperty(“mail.smtp.host”, host); properties.put(“mail.smtp.auth”, “true”); MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put(“mail.smtp.ssl.enable”, “true”); properties.put(“mail.smtp.ssl.socketFactory”, sf); // 獲取默認session對象 Session session = Session.getDefaultInstance(properties,new Authenticator(){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( PropertiesUntil.Properties(“account”), PropertiesUntil.Properties(“password”)); //發件人郵件用戶名、密碼 } }); try{ // 創建默認的 MimeMessage 對象 MimeMessage message = new MimeMessage(session); // Set From: 頭部頭字段 message.setFrom(new InternetAddress(from)); // Set To: 頭部頭字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: 頭部頭字段 message.setSubject(title); // 設置消息體 message.setText(body); // 發送消息 Transport.send(message); return true; }catch (MessagingException mex) { return false; } } }
PropertiesUntil.Properties(“account”) 發送人郵箱賬號
PropertiesUntil.Properties(“password”) 發送人郵件密碼,注意是剛剛生成的
授權碼
String email,String title,String body 三個參數分別為收件人郵箱,標題,正文
三五互聯優質企業郵箱服務商,提供安全穩定,簡單易用,高性價比的企業郵箱。按需自由定制,不限空間,極速收發,能夠滿足用戶對企業郵箱的不同需求。多種反垃圾郵件算法,99.9%精準度,智能過濾,減少垃圾郵件干擾。支持小程序收發郵件,隨時隨地移動辦公。而且價格實惠,還可以免費試用,7×24小時專業團隊服務支持!
高性價比企業郵箱開通鏈接:http://m.shinetop.cn/services/mail/