1、maven環境
<!-- 發送郵件 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>
2、編寫郵箱發送工具類MaliUtil(163郵箱)
package com.ldf.cnblogs.utils; import java.util.Properties; import javax.mail.Address; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class MailUtil { public static boolean sendMail(String email,String title, String emailMsg) { String from = "換成發件人郵箱地址"; // 郵件發送人的郵件地址 String to = email; // 郵件接收人的郵件地址 final String username = "換成發件人郵箱賬戶"; //發件人的郵件帳戶 final String password = "換成發件賬戶的授權碼"; //發件人的郵件授權碼 //定義Properties對象,設置環境信息 Properties props = System.getProperties(); //設置郵件服務器的地址 props.setProperty("mail.smtp.host", "smtp.163.com"); // 指定的smtp服務器 props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.transport.protocol", "smtp");//設置發送郵件使用的協議 //創建Session對象,session對象表示整個郵件的環境信息 Session session = Session.getInstance(props); //設置輸出調試信息 session.setDebug(true); try { //Message的實例對象表示一封電子郵件 MimeMessage message = new MimeMessage(session); //設置發件人的地址 message.setFrom(new InternetAddress(from)); //設置主題 message.setSubject(title); //設置郵件的文本內容 //message.setText("Welcome to JavaMail World!"); message.setContent((emailMsg),"text/html;charset=utf-8"); //從session的環境中獲取發送郵件的對象 Transport transport=session.getTransport(); //連接郵件服務器 transport.connect("smtp.163.com",25, username, password); //設置收件人地址,並發送消息 transport.sendMessage(message,new Address[]{new InternetAddress(to)}); transport.close(); return true; } catch (MessagingException e) { e.printStackTrace(); return false; } } }
3、調用郵箱發送工具類
public boolean sendEmail(String email) { String activeCode = ""; for (int i = 0;i<6;i++){ activeCode=(int)(Math.random()*10)+activeCode; } return MailUtil.sendMail(email,"博客園賬戶郵箱激活", "驗證碼為"+activeCode); }
4、163郵箱配置



至此,163郵箱才能夠成功發送郵件
