1 package mail;
2
3 import java.util.Properties;
4 import java.util.Random;
5
6 import javax.mail.Authenticator;
7 import javax.mail.MessagingException;
8 import javax.mail.PasswordAuthentication;
9 import javax.mail.Session;
10 import javax.mail.Transport;
11 import javax.mail.internet.AddressException;
12 import javax.mail.internet.InternetAddress;
13 import javax.mail.internet.MimeMessage;
14 import javax.mail.internet.MimeMessage.RecipientType;
15
16 import org.junit.Test;
17 /**
18 * javamail第一例
19 * @author 刘乃杰
20 * 17.6.14
21 *
22 */
23
24 public class Demo02 {
25 @Test
26 public void fun1() throws AddressException, MessagingException{
27 /**
28 * 1.得到session
29 */
30 Properties props=new Properties();
31 props.setProperty("mail.host","smtp.163.com"); //设置邮件服务器地址 /*不同邮箱:smtp:xxx.com*/
32 props.setProperty("mail.smtp.auth","true"); //设置邮件服务器是否需要认证
33 //创建认证器
34 Authenticator auth=new Authenticator() {
35 public PasswordAuthentication getPasswordAuthentication(){
36 return new PasswordAuthentication("xxx","xxx");
37 //指定用户名和密码
38 /*用户名不需加后缀 例:xxx@163.com 只需写xxx*/
39 }
40 };
41 //获取session对象
42 Session session=Session.getInstance(props,auth);
43
44 /**
45 * 2.创建mimemessage
46 */
47 MimeMessage msg=new MimeMessage(session);
48 msg.setFrom(new InternetAddress("xxx")); //设置发件人
49 msg.addRecipient(RecipientType.TO,new InternetAddress("xxxx")); //设置收件人
50 // msg.addRecipient(RecipientType.CC,new InternetAddress("xxxx")); //类型为抄送
51 // msg.addRecipient(RecipientType.BCC,new InternetAddress("xxxx"));//类型为密送
52
53 msg.setSubject("这是一封测试邮件"); //设置邮件的主题
54 //指定内容,及内容的mime类型
55 Random rand = new Random();
56 int yzm = rand.nextInt(1000);
57 msg.setContent("验证码为:["+yzm+"]","text/html;charset=utf-8");
58 /**
59 * 3.发邮件
60 */
61 Transport.send(msg);
62 }
63 }