首先在pom.xml的dependencies标签下添加依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.3.2</version>
</dependency>
创建SendEmail.java,测试如下。封装成方法,在需要发邮件的地方调用就行了。
public static void main(String[] args) throws EmailException, MalformedURLException {
Email email = new HtmlEmail();
email.setHostName("smtp.qq.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("xxx@qq.com", "xxxx"));
email.setSSLOnConnect(true);
email.setFrom("xxx@qq.com", "社区");
email.setSubject("异常信息");
email.setContent("<a href='www.baidu.com'></a>","text/html;charset=utf-8");
email.addTo("bbbb@live.com");
email.send();
}
注意
邮箱需要开启smtp服务
更多示例见官网:http://commons.apache.org/proper/commons-email/userguide.html