PS:使用的时候请修改配置文件和代码中的邮箱地址和密码
最近项目中新增了一个功能:自定义异常信息,保存到数据库表中,通过定时任务实时的把异常信息邮件通知给网站维护人员。
网上找了一些示例,整理如下:
示例1:最基本的demo,配置信息在代码里写死,不方便修改
示例2:可配置demo,有文本和html两种发送方式
示例3:可配置,支持附件上传
开发中碰到的的异常
DEBUG SMTP: trying to connect to host "localhost", port 25, isSSL false javax.mail.SendFailedException: Send failure (javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25 (java.net.ConnectException: Connection refused: connect)) at javax.mail.Transport.send(Transport.java:163) at javax.mail.Transport.send(Transport.java:48) at com.wasu.util.Test.main(Test.java:51) Caused by: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25 (java.net.ConnectException: Connection refused: connect) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654) at javax.mail.Service.connect(Service.java:254) at javax.mail.Service.connect(Service.java:85) at javax.mail.Service.connect(Service.java:70) at javax.mail.Transport.send(Transport.java:94) ... 2 more Caused by: java.net.ConnectException: Connection refused: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:529) at java.net.Socket.connect(Socket.java:478) at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927) ... 7 more
原因:之前使用的是maven库中的mail-1.4.7.jar包
解决办法:使用mail.jar的本地包(此包在附件demo中有)
不知道这2个包到底有啥区别,反正用1.4.7的包怎样都不行,一直爆上面的异常,使用mail.jar的包就搞定了。
15年还运行正常的代码16年拿来使用的时候出问题了:
javax.mail.SendFailedException: Sending failed;
nested exception is:
javax.mail.MessagingException: Unknown SMTP host: smtp.163.com;
nested exception is:
java.net.UnknownHostException: smtp.163.com
at javax.mail.Transport.send0(Transport.java:219)
at javax.mail.Transport.send(Transport.java:81)
at email.send1.Test.main(Test.java:54)
15年的时候使用163和qq都可以正常发送邮件的,16年使用的时候出现上面的错误,最终我换成企业邮箱来发送邮件就正常了。