問題:用java實現服務器發送激活碼到用戶郵件。html
步驟一:若是是我的的話,確保在本地安裝郵件服務器(易郵服務器)和郵件客戶端(foxmail)。java
步驟二:導入jar包 mail.jar,其餘的須要什麼協議導什麼jar。服務器
package cn.itcast.store.utils; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage.RecipientType; public class MailUtils { public static void sendMail(String email, String emailMsg) throws AddressException, MessagingException { // 1.建立一個程序與郵件服務器會話對象 Session Properties props = new Properties(); //設置發送的協議 //props.setProperty("mail.transport.protocol", "SMTP"); //設置發送郵件的服務器 //props.setProperty("mail.host", "smtp.126.com"); //props.setProperty("mail.smtp.auth", "true");// 指定驗證爲true // 建立驗證器 Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { //設置發送人的賬號和密碼 return new PasswordAuthentication("admin", "admin@store.com"); } }; Session session = Session.getInstance(props, auth); // 2.建立一個Message,它至關因而郵件內容 Message message = new MimeMessage(session); //設置發送者 message.setFrom(new InternetAddress("admin@store.com")); //設置發送方式與接收者 message.setRecipient(RecipientType.TO, new InternetAddress(email)); //設置郵件主題 message.setSubject("用戶激活"); // message.setText("這是一封激活郵件,請<a href='#'>點擊</a>"); String url="http://localhost:8080/MyTomcat/UserServlet?method=active&code="+emailMsg; String content="<h1>來自購物天堂的激活郵件!激活請點擊如下連接!</h1><h3><a href='"+url+"'>"+url+"</a></h3>"; //設置郵件內容 message.setContent(content, "text/html;charset=utf-8"); // 3.建立 Transport用於將郵件發送 Transport.send(message); } public static void main(String[] args) throws AddressException, MessagingException { MailUtils.sendMail("aaa@store.com", "abcdefg"); } }