需求分析java
客戶須要註冊某一個app,選擇郵箱註冊。spring
客戶操做服務器
打開app,點擊郵箱註冊,會收到一個跳轉提示,跳往郵箱驗證頁面。session
app操做app
傳入後臺兩個參數:郵箱地址、驗證內容maven
後臺操做ide
0.導入java自帶的發送郵件的jar包,個人是maven工程code
pom.xml文件裏添加xml
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.2</version> </dependency>
1.接收參數ip
實現層代碼以下
import java.util.Date; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.Session; import javax.mail.Message.RecipientType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import org.springframework.stereotype.Service; import com.zhiji.caren.common.Constant; import com.zhiji.caren.common.ResultCode; import com.zhiji.caren.common.ResultMsg; import com.zhiji.caren.common.ResultObject; import com.zhiji.caren.service.SendEailService; @Service public class SendEmailServiceImpl implements SendEailService { @Override public ResultObject actMail(String Email, String iCode) { ResultObject resultObject = new ResultObject(); try { Properties props = System.getProperties(); props.setProperty("mail.transport.protocol", "smtp"); // 郵箱協議 props.put("mail.smtp.host", "smtp.qq.com");// 郵箱服務器 props.put("mail.smtp.auth", "ture");// 是否須要身份驗證 props.put("mail.smtp.port", 25);// 服務器端口 Session mailSession = Session.getDefaultInstance(props); // 設置session,和郵件服務器進行通信。 MimeMessage message = new MimeMessage(mailSession);// 設置郵件類型 MimeMultipart mp = new MimeMultipart(); BodyPart body = new MimeBodyPart(); message.setSubject(MimeUtility.encodeText("xx公司")); // 設置主題 // 設置正文 body.setContent("你好!" + "\n" + "\n" + "歡迎加入XX公司。你的註冊郵箱爲:" + Email + "\n" + "\n" + "你用於註冊XX公司的驗證碼爲:" + "\n" + "\n" + iCode + ",驗證經過後便可登陸,如非本人操做請忽略。" + "\n" + "\n" + "\n", "text/plain;charset=GBK"); // mp.addBodyPart(body); message.setContent(mp); message.setHeader("xx公司郵箱驗證", "xx公司郵箱驗證"); // 設置郵件標題 message.setSentDate(new Date());// 設置郵件發送日期 InternetAddress address = new InternetAddress("123456@qq.com");//發件人帳號 message.setFrom(address); // 設置郵件發送者的地址 InternetAddress toAddress = new InternetAddress(Email); // 設置郵件接收方的地址 message.setRecipient(RecipientType.TO, toAddress);// 添加郵件接受方地址 message.saveChanges(); javax.mail.Transport transport = null;// 建立一個郵件發送實例transport transport = mailSession.getTransport("smtp");//規定tranport使用協議 // 使用transport transport.connect("smtp.qq.com", "123456@qq.com", "123456"); //發送郵件 transport.sendMessage(message, message.getAllRecipients()); transport.close(); resultObject.setResultCode(ResultCode.SUCCESS); resultObject.setResultMsg(ResultMsg.MSG_SUCCESS); } catch (Exception ex) { ex.printStackTrace(); resultObject.setResultCode(ResultCode.FAILED); resultObject.setResultMsg(ResultMsg.MSG_FAILED); } return resultObject; } }