java Mail如何发送邮件
1.应用场景:在系统需要发送与用户相关的消息时,而用户不在线,可以采取发送邮件的方式,使用户了解最新的系统情况 或者发送验证码等验证场景
2.实验环境 主要使用mail.jar和activation.jar两个包
3.使用一份简单的邮件
public void sendMail() throws AddressException, MessagingException{ /* * 1.得到session */ Properties properties=new Properties(); properties.setProperty("mail.host", "smtp.163.com"); properties.setProperty("mail.smtp.auth", "true"); //账户信息测试 Authenticator auth =new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("zhou_s1", "xxx"); //这里是账户名和密码 } }; Session session =Session.getInstance(properties,auth); /* * 2.创建消息message */ MimeMessage message=new MimeMessage(session); message.setFrom(new InternetAddress("zhou_s1@163.com"));//设置发件人 message.setRecipients(RecipientType.TO, "583350208@qq.com");//设置收件人 //message.setRecipients(RecipientType.CC, "teacher.z@qq.com");//设置抄送 //message.setRecipients(RecipientType.BCC, "583350208@qq.com");//暗送给谁 message.setSubject("这一份来自周松测试的垃圾邮件--javamail"); message.setContent("test test test !!!","text/html;charset=utf-8"); /* * 3.发送 */ Transport.send(message); }
4.一份带有附件的邮件
public void sendMailMore() throws AddressException, MessagingException, IOException{ /* * 1.得到session */ Properties properties=new Properties(); properties.setProperty("mail.host", "smtp.163.com"); properties.setProperty("mail.smtp.auth", "true"); //账户信息测试 Authenticator auth =new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("zhou_s1", "xxx"); } }; Session session =Session.getInstance(properties,auth); /* * 2.创建消息message */ MimeMessage message=new MimeMessage(session); message.setFrom(new InternetAddress("zhou_s1@163.com"));//设置发件人 message.setRecipients(RecipientType.TO, "583350208@qq.com");//设置收件人 message.setSubject("这是一份含有附件的邮件---测试使用--javamail"); /******************************************************/ /* * 附件的主体流程 附件含有多个组成部分 简称多部件 * */ MimeMultipart list =new MimeMultipart(); //1.邮件主要内容 MimeBodyPart MimeBodyPart part1 =new MimeBodyPart(); //1.1.内容 part1.setContent("一份含有附件的测试邮件", "text/html;charset=utf-8"); //1.2将主体添加到邮件中去 list.addBodyPart(part1); //2.1.邮件附件里面的内容 MimeBodyPart part2 =new MimeBodyPart(); //2.2.附件 File file =new File("G:/JAVAtest/Merge.mp3"); part2.attachFile(file); part2.setFileName(MimeUtility.encodeText("Merge.mp3")); //2.3将主体添加到邮件中去 list.addBodyPart(part2); //3.最后将多部件添加到消息中去 message.setContent(list); //发送 Transport.send(message); }
测试完毕!
恐惧源于无知,代码改变世界