這里使用的是本機的郵箱服務器 ,
代碼執行條件:
1.·郵箱服務器 , 下載地址 密碼 s4xn
郵箱服務器配置:
1):安裝
2):打開服務器
紅色部分是默認賬號,不用處理
3)系統設置 》點擊工具 》服務器設置》
4)創建賬號
2 .郵箱客戶端 ,可以到官網上下載:
1.郵箱客戶端的安裝
接收和發送郵件服務器: localhost
3 .mail.jar 包
4.Util工具類
package com.study.mail; 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.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage.RecipientType; public class MailUtils { // email :email 地址 ,subject 郵箱主題,emailMsg 郵箱信息 public static void sendMail(String email,String subject, String emailMsg) throws AddressException, MessagingException { // 1.創建一個程序與郵件服務器會話對象 Session Properties props = new Properties(); props.setProperty("mail.transport.protocol", "SMTP");//發送郵件的協議 props.setProperty("mail.host", "localhost");//發送郵件的服務器地址 props.setProperty("mail.smtp.auth", "true");// 指定驗證為true // 創建驗證器 Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("tom", "123456");//發送郵件的賬號認證 } }; Session session = Session.getInstance(props, auth); // 2.創建一個Message,它相當於是郵件內容 Message message = new MimeMessage(session); message.setFrom(new InternetAddress("tom@study.com")); // 設置發送者 message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 設置發送方式與接收者 message.setSubject(subject);//設置郵件的主題 // message.setText("這是一封激活郵件,請<a href='#'>點擊</a>"); //設置郵件的內容 message.setContent(emailMsg, "text/html;charset=utf-8"); // 3.創建 Transport用於將郵件發送 Transport.send(message); } }
測試類:
package com.study.mail; import javax.mail.MessagingException; import javax.mail.internet.AddressException; public class sendMailTest { public static void main(String[] args) throws AddressException, MessagingException { MailUtils.sendMail("lucy@study.com","測試郵件","這是一封測試郵件"); } }