使用apache.commons.mail包发送邮件,例子

来源:互联网 发布:javascript 页面滚动 编辑:程序博客网 时间:2024/04/27 07:58

以前都是用javamail,感觉不爽,看了下apache.commons.mail觉得很好用,写了一下

需要下载 commons-email-1.0.jar包,地址:http://download.csdn.net/sort/tag/commons-email-1.0

申请了一个邮箱,测试成功,(注意,一定要设置邮箱开启stmp!)

代码如下:注意,运行时候注意附件地址!

package lihan;
import org.apache.commons.mail.*; 
/** 
* 使用apache mail开源项目发送邮件示例 
* @author 李晗
*/ 
public class test { 
     //程序主方法 
public static void main(String[] args)throws Exception { 
   test as=new test(); 
     String host = "smtp.sina.com"; 
         String from = "javalihan@sina.com"; 
         String username = "javalihan"; 
         String password = "javame"; 
         //接收者邮箱 
         String to = "lbl2006@qq.com"; 
         String subject="这是李晗的测试主题!"; 
         String mailConent="这是李晗的测试邮件"; 
          //调用发送附件邮件方法 
   as.sendAttachmentMail(host, from, username, password, to, subject, mailConent); 

   public boolean sendAttachmentMail(String host,String from,String username, 
    String password,String to,String subject,String mailConent)throws Exception{ 
       //创建附件对象 
    EmailAttachment attachment = new EmailAttachment(); 
                /*附件的地址*/      
    attachment.setPath("E://commons-email-1.0.rar");   
                      //设定为附件 
          attachment.setDisposition(EmailAttachment.ATTACHMENT); 
          /*附件的描述*/ 
          attachment.setDescription("jPortMap项目设计附件文档"); 
          /*附件的名称,必须和文件名一致*/ 
          attachment.setName("Eclipse中文教程.pdf"); 
          /*new一个HtmlEmail发送对象*/ 
    HtmlEmail email = new HtmlEmail();   
       email.setAuthentication(username, password); 
    email.setHostName(host); 
    email.addTo(to, from); 
    email.setFrom(from); 
    email.setSubject(subject); 
          //注意,发送内容时,后面这段会让中文正常显示,否则乱码 
    email.setCharset("GB2312"); 
    email.setHtmlMsg("<html>这是封测试附件邮件</html>"); /*邮件内容*/ 
          //添加附件对象 
    email.attach(attachment); 
    //发送 
    email.send(); 
    System.out.println("带符件的邮件发送成功!"); 
    return true; 


}


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/lihan6415151528/archive/2008/12/11/3496827.aspx