【发送激活邮件】
邮件发送的相关的概念:
* 邮箱服务器 :如果一台电脑安装了邮箱服务器的软件,这台电脑称为是邮箱服务器.
* 电子邮箱 :其实就是邮箱服务器上的一块空间,通过电子邮箱账号访问这块空间的数据.
* 收发邮件的协议 :
* 发邮件:SMTP协议:SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。 25默认端口号
* 收邮件:POP3协议:POP3,全名为“Post Office Protocol - Version 3”,即“邮局协议版本3”。是TCP/IP协议族中的一员。默认端口是110
* 收邮件:IMAP协议:IMAP(Internet Mail Access Protocol,Internet邮件访问协议)以前称作交互邮件访问协议(Interactive Mail Access Protocol)。IMAP是斯坦福大学在1986年开发的一种邮件获取协议。
* 收发邮件的过程:
核心代码的实现:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
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;
public class MailUtils {
public static void sendMail(String to,String code){
try {
//获取连接
Properties properties =new Properties();
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("service@store.com", "111");
}
});
//构建邮件
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("service@store.com"));
//设置收件人
//to 收件人 、CC抄送、BCC密送、暗送
message.setRecipient(RecipientType.TO, new InternetAddress(to));
//主题
message.setSubject("<h>来自中国路人甲的一封激活邮件</h>");
//设置正文
message.setContent("<h1>来自购物天堂黑马官方商城的激活邮件:请点击下面链接激活!</h1><h3><a href='http://localhost:8080/store_v2.0/UserServlet?method=active&code="+code+"'>http://localhost:8080/store_v2.0/UserServlet?method=active&code="+code+"</a></h3>", "text/html;charset=UTF-8");
//发送邮件
Transport.send(message);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}