導(dǎo)包
<!– 發(fā)送郵件 –> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.0</version> </dependency> </dependencies> qq郵箱開啟POP3/SMTP服務(wù)
設(shè)置-.>賬戶->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務(wù)
開啟POP3/SMTP服務(wù)
生成授權(quán)碼后將授權(quán)碼保存,后面會用
代碼
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; // 發(fā)件人電子郵箱 String from = PropertiesUntil.Properties(“account”); // 指定發(fā)送郵件的主機(jī)為 smtp.qq.com String host = “smtp.qq.com”; //QQ 郵件服務(wù)器 // 獲取系統(tǒng)屬性 Properties properties = System.getProperties(); // 設(shè)置郵件服務(wù)器 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); // 獲取默認(rèn)session對象 Session session = Session.getDefaultInstance(properties,new Authenticator(){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( PropertiesUntil.Properties(“account”), PropertiesUntil.Properties(“password”)); //發(fā)件人郵件用戶名、密碼 } }); try{ // 創(chuàng)建默認(rèn)的 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); // 設(shè)置消息體 message.setText(body); // 發(fā)送消息 Transport.send(message); return true; }catch (MessagingException mex) { return false; } } }
PropertiesUntil.Properties(“account”) 發(fā)送人郵箱賬號
PropertiesUntil.Properties(“password”) 發(fā)送人郵件密碼,注意是剛剛生成的
授權(quán)碼
String email,String title,String body 三個參數(shù)分別為收件人郵箱,標(biāo)題,正文
西部數(shù)碼優(yōu)質(zhì)企業(yè)郵箱服務(wù)商,提供安全穩(wěn)定,簡單易用,高性價(jià)比的企業(yè)郵箱。按需自由定制,不限空間,極速收發(fā),能夠滿足用戶對企業(yè)郵箱的不同需求。多種反垃圾郵件算法,99.9%精準(zhǔn)度,智能過濾,減少垃圾郵件干擾。支持小程序收發(fā)郵件,隨時隨地移動辦公。而且價(jià)格實(shí)惠,還可以免費(fèi)試用,7×24小時專業(yè)團(tuán)隊(duì)服務(wù)支持!
高性價(jià)比企業(yè)郵箱開通鏈接:http://bingfeng168.cn/services/mail/