【commons】邮件发送工具——commons-email
一、概述
直接通过官网的overview进行了解,一句话概括如下:
Commons Email aims to provide a API for sending email. It is built on top of the Java Mail API, which it aims to simplify.
Commons Email 旨在提供发送邮件的API,它是简历在Java Mail之上的,目的是简化它。
二、入门
1.获取commons-email
采用maven构建的坐标如下:
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-email -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>
如需下载Jar包,请登陆官网下载:http://commons.apache.org/proper/commons-email/download_email.cgi
2.入门程序
发送简单文本邮件
public static void main(String[] args) throws Exception{
Email email = new SimpleEmail();
email.setHostName("smtp.qq.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("775992759@qq.com", "你的授权码"));
email.setSSLOnConnect(true);
email.setFrom("775992759@qq.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("2126802032@qq.com");
email.send();
System.out.println("发送成功!");
}
关于授权码的设置请参见QQ邮箱(其它邮箱的SMTP的开启设置请使用搜索引擎)的帮助:http://service.mail.qq.com/cgi-bin/help?id=28
结果:
发送带附件的邮件:
public static void main(String[] args) throws Exception{
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("D:\\test\\1.jpg");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Picture of John");
attachment.setName("John.jpg");
// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("smtp.qq.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("775992759@qq.com", "你的授权码"));
email.setSSLOnConnect(true);
email.addTo("2126802032@qq.com");
email.setFrom("775992759@qq.com");
email.setSubject("The picture");
email.setMsg("Here is the picture you wanted");
// add the attachment
email.attach(attachment);
// send the email
email.send();
System.out.println("发送成功!");
}
结果:
更多,请参见官网入门介绍:http://commons.apache.org/proper/commons-email/userguide.html