在Spring项目中须要增加监控功能。监控过程中发现异常时。须要邮件报警。最初选择用javamail发送,代码量比較大(相对于spring发送)。终于选择Spring邮件发送~
以下贴一下实现的代码以及注意事项;
代码结构非常easy一个java类和一个xml文件,用到三个jar包,demo下载地址http://download.csdn.net/detail/jeofey/8892859
这里仅仅是简单的发送,假设须要发送附件或者HTML格式的邮件的话,代码在文章末尾
- package mail;
- import javax.mail.MessagingException;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.FileSystemXmlApplicationContext;
- import org.springframework.mail.SimpleMailMessage;
- import org.springframework.mail.javamail.JavaMailSender;
- /**
- * @author Owner
- * springMail发送邮件
- * SendMail.java
- */
- public class SendMail {
- public ApplicationContext ctx = null;
- public SendMail() {
- ctx = new FileSystemXmlApplicationContext("src/mail/applicationContext-mail.xml");
- }
- /**
- * 主測试方法
- *
- * @throws MessagingException
- */
- public static void main(String[] args) {
- new SendMail().sendMail();
- }
- /**
- * 发送简单邮件
- */
- public void sendMail() {
- JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");// 获取JavaMailSender
- SimpleMailMessage mail = new SimpleMailMessage();
- try {
- mail.setTo("aaaa@qq.com");// 接受者
- mail.setFrom("bbbb@163.com");// 发送者
- mail.setSubject("s邮件主题");// 主题
- mail.setText("springMail 的简单发送測试");// 邮件内容
- sender.send(mail);
- System.out.println("发送完成");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
注意事项:在读取xml配置文件时,用的是FileSystemXmlApplicationContext实现类,在书写路径的时候不能仅仅写文件名称,虽然java文件和xml文件是在同一文件夹下。
假设收件人有多个时,mail.setTo("aaaa@qq.com")。mail.setTo("cccc@qq.com")....
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:jee="http://www.springframework.org/schema/jee"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
- http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
- <bean id="mailSender"
- class="org.springframework.mail.javamail.JavaMailSenderImpl">
- <property name="host">
- <value>smtp.163.com</value>
- </property>
- <property name="javaMailProperties">
- <props>
- <prop key="mail.smtp.auth">true</prop>
- <prop key="mail.smtp.timeout">25000</prop>
- <prop key="mail.smtp.socketFactory.fallback">false</prop>
- <prop key="mail.smtp.starttls.enable">true</prop>
- <!-- 这里是配置ssl 主要是个,Gmail
- <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
- -->
- </props>
- </property>
- <property name="username">
- <value>bbbb@163.com</value> <!-- 邮箱的username。注意要写正确了 -->
- </property>
- <property name="password">
- <value>*****</value> <!-- 邮箱password -->
- </property>
- <property name="port">
- <value>25</value>
- </property>
- </bean>
- </beans>
注意问题:username须要书写正确,必须是发送邮件中设定好的username,假设没设置。默认是邮件地址。当初这里没写正确,验证时出现了异常;
- 七月 12, 2015 8:02:57 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
- 信息: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@16d835f: display name [org.springframework.context.support.FileSystemXmlApplicationContext@16d835f]; startup date [Sun Jul 12 20:02:57 CST 2015]; root of context hierarchy
- 七月 12, 2015 8:02:58 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
- 信息: Loading XML bean definitions from file [D:liuworkspacemyspmainsrcmailapplicationContext-mail.xml]
- 七月 12, 2015 8:02:58 下午 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
- 信息: Bean factory for application context [org.springframework.context.support.FileSystemXmlApplicationContext@16d835f]: org.springframework.beans.factory.support.DefaultListableBeanFactory@13911fe
- 七月 12, 2015 8:02:58 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
- 信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@13911fe: defining beans [mailSender]; root of factory hierarchy
- org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException
- at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:416)
- at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:308)
- at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:297)
- at mail.SendMail.sendMail(SendMail.java:41)
- at mail.SendMail.main(SendMail.java:28)
- Caused by: javax.mail.AuthenticationFailedException
- at javax.mail.Service.connect(Service.java:306)
- at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:389)
- ... 4 more
发件结果:
发送html格式和发送附件的代码
- /**
- * 发送带有正文是html的邮件
- *
- * @throws MessagingException
- */
- public void sendHTML() throws MessagingException {
- JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");// 获取JavaMailSender
- // bean
- MimeMessage mm = sender.createMimeMessage();
- MimeMessageHelper helper = new MimeMessageHelper(mm, true, "utf-8");
- try {
- helper.setTo("aaaa@qq.com");// 接受者
- helper.setFrom("bbbb@163.com");// 发送者
- helper.setSubject("邮件主题");// 主题
- helper.setText("<html><head></head><body><h1>hello!!beckham</h1></body></html>",true);// 第二个參数代表发送的是正文是html
- sender.send(mm);
- System.out.println("发送完成");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 发送带有附件的邮件
- *
- * @throws MessagingException
- */
- public void sendFileMail() throws MessagingException {
- JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");// 获取JavaMailSender
- // bean
- MimeMessage mm = sender.createMimeMessage();
- MimeMessageHelper helper = new MimeMessageHelper(mm, true, "utf-8");
- try {
- helper.setTo("aaaa@qq.com");// 接受者
- helper.setFrom("bbbb@163.com");// 发送者
- helper.setSubject("邮件主题");// 主题
- helper.setText("邮件内容");// 邮件内容
- //多个附件文件
- ClassPathResource in = new ClassPathResource("附件.txt");
- ClassPathResource in2 = new ClassPathResource("struts.xml");
- //MimeUtility.encodeWord()解决附件的文件名称为中文问题
- helper.addAttachment(MimeUtility.encodeWord(in.getFilename()), in);
- helper.addAttachment(MimeUtility.encodeWord(in2.getFilename()), in2);
- sender.send(mm);
- System.out.println("发送完成");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }