JavaMail應用場合主要是發送驗證碼或激活賬號
首先:創建JavaMail工具類
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; /** * 發送賬號激活郵件 * @author Zenz * */ public class MailUtils { /** *@param: usermail 郵件接收賬號 *@param: code 激活驗證碼 **/ public static void sendMail(String usermail, String code) throws Exception{ //1.設置郵件參數 Properties prop = new Properties(); //1.1 指定協議 prop.put("mail.transport.protocol", "smtp"); //1.2 主機 prop.put("mail.smtp.host", "服務器IP地址"); //1.3 端口號 prop.put("mail.smtp.port", 25); //1.4 用戶密碼認證 prop.put("mail.smtp.auth", "ture"); //1.5 調試模式 prop.put("mail.debug", "ture"); // 2.創建一個郵件的會話 Session session = Session.getDefaultInstance(prop); //3.創建郵件體對象 MimeMessage message = new MimeMessage(session); //4.設置郵件體參數 //4.1 郵件標題 message.setSubject("XXX賬號激活"); //4.2 發送時間 message.setSentDate(new Date()); //4.3 發件人 message.setSender(new InternetAddress("[email protected]")); //4.4 收件人 message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(usermail)); //4.5 郵件內容 message.setContent("<h1>點擊下面鏈接完成激活</h1> <h3><a href='http://xx<!-- 激活賬號的action方法-->xx.action? code="+code+"'>http://xx<!-- 激活賬號的action方法-->xx.action? code="+code+"</a></h3>", "text/html;charset=UTF-8"); //保存郵件(可選) message.saveChanges(); //5.發送 Transport trans = session.getTransport(); trans.connect("service","root"); trans.sendMessage(message, message.getAllRecipients()); trans.close(); } }
使用:在保持賬號信息到數據庫的同時,調用javamail發送郵件
import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * Created by Zenz. */ @Service("userService") public class UserServiceImpl implements UserService { @Resource private UserDao userDao; @Override public void save(User user) throws Exception { user.setState(0);//0表示未激活 String code = UUIDUtils.getUUID().replace("-","")+ UUIDUtils.getUUID().replace("-",""); user.setCode(code); userDao.save(user); //發送激活碼 MailUtils.sendMail(user.getEmail(),code); } }