一个简单的关于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("发送完毕"); } }