Commons Email是apache commons库中的一个组件,对java mail做了一些个封装,提供能为简化的API供开发者使用。它依赖于javax.mail 。
首先下载commons-email-1.4.jar 和 javax.mail.jar ,并设置build path。
下面是一个简单的工具类,可以向指定的地址发送文本邮件。
package com.hzfi.flume; import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; /** * @author liny * 邮件发送工具类 */ public class MailUtil { private static String _USER_NAME_ = "li222@qq.cn"; private static String _PASSWORD_ = "222"; private static String _SMTP_ADDRESS_ = "smtp.exmail.qq.com"; private final static int _SMTP_PORT_SSL_ = 465; private static String from = "li222@qq.cn";
public static void sendMail(String toAddress, String subject, String content){ Email email = new SimpleEmail(); email.setHostName(_SMTP_ADDRESS_); email.setSmtpPort(_SMTP_PORT_SSL_); email.setAuthenticator(new DefaultAuthenticator(_USER_NAME_, _PASSWORD_)); //email.setSSLOnConnect(true); email.setSSL(true);//commons-mail-1.1支持的方法,1.4中使用setSSLOnConnect(true)代替 try { email.setFrom(from); email.setSubject(subject); email.setMsg(content); email.addTo(toAddress); email.send(); } catch (EmailException e) { e.printStackTrace(); } } public static void main(String[] args){ //test String subject = "测试邮件"; String content = "test test test。。。测试内容。。。这是从MailUtil.java发来的。"; String to = "l333@qq.cn"; MailUtil.sendMail(to, subject, content); } }
li222@qq.cn