目标: err级别发送邮件 ,要求美观 ,信息详细
开工:
材料: 三个jar ,版本不建议高,不能低。
方便起见,打包下载即可 http://pan.baidu.com/s/1mgmfyvY
步奏:
1 配置文件 :log4j.properties
log4j.appender.mail=org.apache.log4j.net.SMTPAppender log4j.appender.mail.Threshold=ERROR #BufferSize设置缓存多大时触发发送
log4j.appender.mail.BufferSize=0
log4j.appender.mail.From=chenpenghui@loongtao.com log4j.appender.mail.SMTPHost=smtp.exmail.qq.com #very import 非常重要 SMTPUsername log4j.appender.mail.SMTPUsername=chenpenghui@loongtao.com log4j.appender.mail.SMTPPassword=****** log4j.appender.mail.Subject=Log4J-Message-LoginSinaWeiboCookie log4j.appender.mail.To=chenpenghui@loongtao.com #log4j.appender.mail.layout=org.apache.log4j.PatternLayout log4j.appender.mail.layout=com.test.DefaultHtmlLayout # 显示代码行数 code line default false log4j.appender.mail.layout.LocationInfo=true #log4j.appender.mail.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
[非相关的没有添加 ,自行添加 ,注释掉的不要打开 ]
红色部分为解决编码 和样式问题
代码如下
DefaultHtmlLayout.java
import org.apache.log4j.HTMLLayout; public class DefaultHtmlLayout extends HTMLLayout { @Override public String getContentType() { return "text/html;charset=UTF-8"; } }
然后err级别的信息能够发送邮件,效果如下
over:
另外附上java发送邮件的code ;
MailUtils.java
1 import java.util.Properties; 2 3 import javax.mail.Message; 4 import javax.mail.MessagingException; 5 import javax.mail.Session; 6 import javax.mail.Transport; 7 import javax.mail.internet.InternetAddress; 8 import javax.mail.internet.MimeMessage; 9 10 public class MailUtils { 11 12 public static void main(String args[]) throws Exception, MessagingException { 13 String host = "smtp.exmail.qq.com";// 发送邮件服务器 14 String from = "xxx@xxx.com"; 15 String to = "xxx@xxx.com"; 16 // new properties 17 Properties props = new Properties(); 18 // Setup mail server 19 props.put("mail.smtp.host", host);// 设置smtp主机 20 props.put("mail.smtp.auth", "true");// 使用smtp身份验证 21 // Get session 22 Session session = Session.getDefaultInstance(props, null); 23 // Define message 24 MimeMessage message = new MimeMessage(session); 25 message.setFrom(new InternetAddress(from)); 26 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 27 message.setSubject("test");// 标题 28 message.setText("http://www.baidu.com/" + "This is test JavaMail");// 内容 29 // http协议部分会自动转换成超链接 30 message.saveChanges(); 31 // Send message 32 Transport transport = session.getTransport("smtp"); 33 System.out.println("正在连接"); 34 transport.connect(host, from, "***"); 35 System.out.println("正在发送"); 36 transport.sendMessage(message, message.getAllRecipients()); 37 System.out.println("邮件发送成功"); 38 } 39 40 }
详细配置自行查看