用commons-email-1.1.jar实现发邮件功能:

直接贴上测试代码,简单清晰,只要修改(邮件服务器地址、名称、密码)就可以使用了

 

简单邮件的发送:

package com.bulktree.mail;

import java.util.Date;

import org.apache.commons.mail.EmailException;

import org.apache.commons.mail.SimpleEmail;

publicclass SimpleMailTest {

    public static void main(String[] args) throws EmailException {

       SimpleEmail email = new SimpleEmail();

       //设置发送主机的服务器地址

       email.setHostName("smtp.163.com");

       //设置收件人邮箱

       email.addTo("");

       //发件人邮箱

       email.setFrom("", "bulktree");

       //如果要求身份验证,设置用户名、密码,分别为发件人在邮件服务器上注册的用户名和密码

       email.setAuthentication("bulktree", "123456");

       //设置邮件的主题

       email.setSubject("Hello, This is My First Email Application");

       //邮件正文消息

       email.setMsg("I am bulktree This is JavaMail Application");

       email.send();

       System.out.println("The SimpleEmail send sucessful!!!");

    }

}

 

带附件邮件发送:

package com.bulktree.mail;

import java.net.MalformedURLException;

import java.net.URL;

import org.apache.commons.mail.EmailAttachment;

import org.apache.commons.mail.EmailException;

import org.apache.commons.mail.MultiPartEmail;

publicclass AttachmentMailTest {

    publicstaticvoid main(String[] args) throws EmailException, MalformedURLException {

//     创建一个Email附件

       EmailAttachment emailp_w_upload = new EmailAttachment();

       emailp_w_upload.setPath("/biao_05.jpg");

//     emailp_w_upload.setURL(new URL(""));

       emailp_w_upload.setDisposition(EmailAttachment.ATTACHMENT);

       emailp_w_upload.setDescription("This is Smile picture");

       emailp_w_upload.setName("bulktree");

//     创建一个email

       MultiPartEmail multipartemail = new MultiPartEmail();

       multipartemail.setHostName("smtp.163.com");

       multipartemail.addTo("", "bulktree");

       multipartemail.setFrom("", "bulktree");

       multipartemail.setAuthentication("bulktree", "123456");

       multipartemail.setSubject("This is a p_w_upload Email");

       multipartemail.setMsg("this a p_w_upload Eamil Test");

       //添加附件

       multipartemail.attach(emailp_w_upload);

       //发送邮件

       multipartemail.send();

       System.out.println("The p_w_uploadEmail send sucessful!!!");

    }

}

 

运行本例子程序需要commons-email-1.1.jar和mail.jar这两个包!