JavaWeb —— JavaMail邮件发送

用户注册时需要给用户填写的邮箱发送一封激活邮件

一、引入jar包:

mail.jar

activation.jar

二、发送邮件的工具类

 1 public class MailUtils extends Thread {
 2     //给用户发送邮件的邮箱
 3     private String from = "xxxxxx@163.com";
 4     //发送邮件的服务器地址
 5     private String host = "smtp.163.com";
 6     //邮箱的用户名
 7     private String username = "xxxxxx";
 8     //邮箱的授权码
 9     private String password = "xxxxxx";
10 
11     private String email;
12     private String emailMsg;
13 
14     public MailUtils(String email, String emailMsg) {
15         this.email = email;
16         this.emailMsg = emailMsg;
17     }
18 
19     @Override
20     public void run() {
21         try {
22             //创建Properties对象,并设置邮件服务器的基本信息
23             Properties properties = new Properties();
24             //设置邮件传输协议为SMTP
25             properties.setProperty("mail.transport.protocol", "SMTP");
26             //设置SMTP服务器地址
27             properties.setProperty("mail.host", host);
28             //设置SMTP服务器是否需要用户验证,需要验证设置为true
29             properties.setProperty("mail.smtp.auth", "true");
30             //创建验证器
31             Authenticator auth = new Authenticator() {
32                 @Override
33                 protected PasswordAuthentication getPasswordAuthentication() {
34                     return new PasswordAuthentication(username,password);
35                 }
36             };
37             //实例化邮件会话Session,发送邮件的环境
38             Session session = Session.getInstance(properties, auth);
39             Message message = sendMail(session, email, emailMsg);
40             //发送邮件
41             Transport.send(message);
42         } catch (MessagingException e) {
43             e.printStackTrace();
44         }
45     }
46 
47     public Message sendMail(Session session, String email, String emailMsg) throws AddressException, MessagingException {
48         //创建一个Message,该内容相当于邮件内容
49         Message message = new MimeMessage(session);
50         //设置发送者
51         message.setFrom(new InternetAddress(from));
52         //设置发送方式与接收者,邮件接收者在调用sendMail()方法时通过参数传递进来
53         message.setRecipient(RecipientType.TO, new InternetAddress(email));
54         //设置发送邮件主题
55         message.setSubject("用户注册");
56         message.setContent(emailMsg, "text/html;charset=utf-8");
57         return message;
58     }
59 }

三、创建该工具类完成邮件发送

1 //user.getEmail():接收邮件的地址,eamilMsg:邮件发送的内容,邮件发送比较慢利用线程提高发送的速度
2 String eamilMsg="xxxxxxxxxxxxx";
3 new MailUtils(user.getEmail(), eamilMsg).start();

 

163邮箱授权码开启:

 

posted @ 2020-11-11 18:26  笺笙  阅读(115)  评论(0编辑  收藏  举报