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.
Some of the mail classes that are provided are as follows:
- SimpleEmail - This class is used to send basic text based emails.
- MultiPartEmail - This class is used to send multipart messages. This allows a text message with attachments either inline or attached.
- HtmlEmail - This class is used to send HTML formatted emails. It has all of the capabilities as MultiPartEmail allowing attachments to be easily added. It also supports embedded images.
- EmailAttachment - This is a simple container class to allow for easy handling of attachments. It is for use with instances of MultiPartEmail and HtmlEmail.
说明:这个是Apache的一个开源项目,是基于另一个开源项目Java Mail上而进行封装的,使用起来更加简单方便。官网:
http://commons.apache.org/email/index.html
首先下载jar包:commons-email-1.2.jar
http://repo1.maven.org/maven2/org/apache/commons/commons-email/1.2/commons-email-1.2.jar
1、先来一个简单文本邮件发送的例子:
注意:email.setHostName("smtp.163.com");
email.setAuthenticator(new DefaultAuthenticator("yuaio@163.com", "yuaio"));
还有email.setTLS(true); email.setSSL(false); 这些都应该是对应的,使用不同的服务商邮箱,这里的HostName需要改一下,同时安全校验也是不同的,据我测试:只有google gmail邮箱这两个校验都需要(google邮箱是我的最爱,好用,快速,最最重要的是安全,给你足够的隐私权。)设email.setTLS(true); email.setSSL(true);
163:两个都不需要校验就能通过;
sina:两个都不需要校验就能通过;
qq邮箱:需要需要校验tls;
email.setDebug(true); 开启debug模式,可以打印一些信息。
2、带附件的邮箱发送:
3、附件图片是url链接的:
4、html格式邮件发送:
异常:开始放在测试项目中还是发送成功的,但是移到另一个项目中,抛异常了:
查找资料有朋友也遇到过,是因为MyEclipse中系统自带的email.jar与导入的mail.jar包冲突不一致引起的,删除系统中的jar包即可:
这里引用这位朋友的方法吧:
用rar打开X:/Program Files/MyEclipse 6.0/myeclipse/eclipse/plugins/com.genuitec.eclipse.j2eedt.core_6.0.1.zmyeclipse601200710/data/libraryset/EE_5/javaee.jar
,然后删除mail,一切就OK了。