一個簡單的關於spring的發送郵件案例:
環境:idea ,spring
-
首先加入關於email的jar
pom.xml中添加
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency>
- 建立用戶entity
package com.slh.email; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; /** * Created by Tyson on 2018/8/10. */ public class MyAuthenticator extends Authenticator { private String username; private String password; public MyAuthenticator() { } public MyAuthenticator(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }
- 創建發送郵件業務類(163郵箱爲例)
package com.slh.email; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; /** * Created by Tyson on 2018/8/10. */ public class SendMail { public void sendMail01() throws MessagingException { /*** * 1. 設置郵件服務器信息 * 2. 進行用戶名面認證 * 3. 創建消息 * 4. 設置收件人和發件人 * 5. 發送郵件 * */ // 定義郵箱服務器配置 Properties props=new Properties(); // 163 郵件服務器地址 props.put("mail.smtp.host", "smtp.163.com"); // 163 郵件服務器端口 props.put("mail.smtp.port", "25"); // 163 郵件服務器認證屬性 props.put("mail.smtp.auth", "true");// 一定要加引號 Session session = Session.getInstance(props, new MyAuthenticator("郵箱地址(如:[email protected])","授權碼(郵箱設置中開啓授權碼)")); Message message = new MimeMessage(session); //發件人 message.setFrom(new InternetAddress("[email protected]")); //收件人 message.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]")); message.setSentDate(new Date());//發送時間 message.setSubject("SGCSGCSGC"); message.setText("SGCSGCSGCSGCSGCSGCSGCSGCSGCSGCSGCSGCSGCSGCSGCSGCSGCSGCSGCSGCSGC"); // 發送 Transport.send(message); } }
- 編輯測試
package com.slh.email; import org.junit.Test; import static org.junit.Assert.*; /** * Created by Tyson on 2018/8/10. */ public class SendMailTest { @Test public void sendMail01() throws Exception { SendMail sendMail = new SendMail(); for(int i=0;i<=22;i++){ sendMail.sendMail01(); } System.out.println("發送完畢"); } }