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_ = "[email protected]"; private static String _PASSWORD_ = "Linyang210"; private static String _SMTP_ADDRESS_ = "smtp.exmail.qq.com"; private final static int _SMTP_PORT_SSL_ = 465; private static String from = "[email protected]"; 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 = "[email protected]"; MailUtil.sendMail(to, subject, content); } }
时间: 2024-10-13 02:42:47