使用Commons Email发送邮件
更多发送类型请参考:http://commons.apache.org/proper/commons-email/userguide.html
使用Commons Email发送邮件首先需要导入依赖包,这里给出maven的坐标:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.4</version> </dependency>
例子很简单,许多东西都已经封装好了的。
例1:
import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.Email; import org.apache.commons.mail.SimpleEmail; public class Test { public static void main(String[] args) throws Exception { try { Email email = new SimpleEmail(); email.setHostName("smtp.exmail.qq.com"); email.setAuthenticator(new DefaultAuthenticator("username", "password")); //设置编码格式,防止乱码 email.setCharset("UTF-8"); email.setFrom("aaa"); email.setSubject("主题"); email.setMsg("发送邮件"); email.addTo("xxx@qq.com"); email.send(); } catch (Exception e) { e.printStackTrace(); } System.out.println("=====>发送完毕!"); } }