一直以来都是用javax.mail来写email发送,看了spring的javamail之后才知道javax.mail臃肿繁杂。
下面总结一下spring javamail的应用:
首先导入使用jar包:activation.jar,commons-logging-1.0.4.jar,mail.jar,spring.jar
1、使用xml配置javamail:
在classpath底下新建application-mail.xml,内容如下:
stmp.163.com true 25000 [email protected] xxxxxx
或者把以上的Beans配置到applicaiont.xml里面也可以。
2、发送Email类:
public class SendMail { public ApplicationContext ctx = null; public SendMail() { //获取上下文 ctx = new ClassPathXmlApplicationContext("applicationContext-mail.xml"); } public void send() { //获取JavaMailSender bean JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender"); SimpleMailMessage mail = new SimpleMailMessage(); //注意SimpleMailMessage只能用来发送text格式的邮件 try { mail.setTo("[email protected]");//接受者 mail.setFrom("[email protected]");//发送者,这里还可以另起Email别名,不用和xml里的username一致 mail.setSubject("spring mail test!");//主题 mail.setText("springMail的简单发送测试");//邮件内容 sender.send(mail); } catch (Exception e) { e.printStackTrace(); } }
发送html格式的Email:
public class SendMail { public ApplicationContext ctx = null; public SendMail() { //获取上下文 ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); } public void send() { //获取JavaMailSender bean JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender"); JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); MimeMessage mailMessage = senderImpl.createMimeMessage(); //设置utf-8或GBK编码,否则邮件会有乱码 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8"); try { messageHelper.setTo(email.getEmail());//接受者 messageHelper.setFrom("[email protected]");//发送者 messageHelper.setSubject("测试邮件");//主题 //邮件内容,注意加参数true,表示启用html格式 messageHelper.setText("hello!!chao.wang
",true); sender.send(mailMessage); } catch (Exception e) { e.printStackTrace(); } }
发送html格式并带有附件的Email:
public class SendMail { public ApplicationContext ctx = null; public SendMail() { //获取上下文 ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); } public void send() { //获取JavaMailSender bean JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender"); JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); MimeMessage mailMessage = senderImpl.createMimeMessage(); //设置utf-8或GBK编码,否则邮件会有乱码 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8"); try { messageHelper.setTo(email.getEmail());//接受者 messageHelper.setFrom("[email protected]");//发送者 messageHelper.setSubject("测试邮件");//主题 //邮件内容,注意加参数true messageHelper.setText("hello!!chao.wang
",true); //附件内容 messageHelper.addInline("a", new File("E:/xiezi.jpg")); messageHelper.addInline("b", new File("E:/logo.png")); File file=new File("E:/测试中文文件.rar"); // 这里的方法调用和插入图片是不同的,使用MimeUtility.encodeWord()来解决附件名称的中文问题 messageHelper.addAttachment(MimeUtility.encodeWord(file.getName()), file); sender.send(mailMessage); } catch (Exception e) { e.printStackTrace(); } }