首页 > 代码库 > 新版本Java邮件发送类

新版本Java邮件发送类

之前曾经做过几个邮件发送类,有兴趣可以查阅前面的帖子。

使用过程中,发现一些不便之处,并作出了改进,将改进后的版本发布如下:

基类及其附属类共三个:(下载地址:http://pan.baidu.com/s/1bn1VkUN)

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.ibm.heyang.util.StringUtil;

/**
 * 邮件发送基类
 * 2013年9月16日13:49:35
 */
public abstract class BaseMailService{
    protected String smtpServer;
    protected String smtpUsername;
    protected String smtpPassword;
    protected String fromMailAddress;
    protected String toMailAddress;
    protected String ccMailAddress;
    protected String bccMailAddress;
    protected boolean testMode; 
    
    public boolean isTestMode() {
        return testMode;
    }

    public void setTestMode(boolean testMode) {
        this.testMode = testMode;
    }

    /**
     * 无参构造函数
     */
    public BaseMailService(){
        
    }
    
    public boolean sendMail(String title,String content) throws Exception{
        return sendMail(title,content,null);
    }
    
    /**
     * 发送邮件的关键函数
     * 
     * @param title
     * @param content
     * @return
     * @throws Exception
     */
    public boolean sendMail(String title,String content,String[] files) throws Exception{
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpServer);
        // 获得邮件会话对象
        Session session = Session.getDefaultInstance(props,new SmtpAuthenticator(smtpUsername, smtpPassword));
        /** *************************************************** */
        // 创建MIME邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(fromMailAddress));// 发件人
        
        // To收件人
        mimeMessage.setRecipients(Message.RecipientType.TO, getInternetAddressArr(toMailAddress));
        
        // Cc收件人
        InternetAddress[] arr=getInternetAddressArr(ccMailAddress);
        if(testMode==false && arr!=null && arr.length>0 ){
            mimeMessage.setRecipients(Message.RecipientType.CC, getInternetAddressArr(ccMailAddress));
        }
        
        // Bcc收件人
        arr=getInternetAddressArr(bccMailAddress);
        if(testMode==false && arr!=null && arr.length>0){
            mimeMessage.setRecipients(Message.RecipientType.BCC, getInternetAddressArr(bccMailAddress));
        }
        
        mimeMessage.setSubject(title);
        mimeMessage.setSentDate(new Date());// 发送日期
        Multipart mp = new MimeMultipart("related");// related意味着可以发送html格式的邮件
        /** *************************************************** */
        BodyPart bodyPart = new MimeBodyPart();// 正文
        bodyPart.setDataHandler(new DataHandler(content,"text/html;charset=utf8"));// 网页格式
        mp.addBodyPart(bodyPart);
        mimeMessage.setContent(mp);// 设置邮件内容对象
        
        if(files!=null && files.length>0){
            for(String affix:files){
                if(affix==null || new File(affix).exists()==false){
                    continue;
                }
                
                //添加附件
                BodyPart messageBodyPart= new MimeBodyPart();
                
                DataSource source = new FileDataSource(affix);
                //添加附件的内容
                messageBodyPart.setDataHandler(new DataHandler(source));
                //添加附件的标题
                messageBodyPart.setFileName(affix);
                mp.addBodyPart(messageBodyPart);
            }
        }
        
        Transport.send(mimeMessage);// 发送邮件
        
        return true;
    }
    
    
    /**
     * Mail地址转化
     * @param mialAddr
     * @return
     * @throws Exception
     */
    protected InternetAddress[] getInternetAddressArr(String mialAddr) throws Exception{
        if(mialAddr==null){
            return null;
        }
        
        if(StringUtil.isBlankString(mialAddr)){
            return null;
        }
        
        String[] arr=mialAddr.split(",");
        
        InternetAddress[] retval=new InternetAddress[arr.length];
        
        for(int i=0;i<arr.length;i++){
            retval[i]=new InternetAddress(arr[i]);
        }
        
        return retval;
    }
    
    /**
     * 保留两位小数
     * @param s
     * @return
     */
    protected String getFormatted(String s){
        float f=Float.parseFloat(s);
        java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#0.00");  
        return df.format(f);
    }

    public String getSmtpServer() {
        return smtpServer;
    }
    public void setSmtpServer(String smtpServer) {
        this.smtpServer = smtpServer;
    }
    public String getSmtpUsername() {
        return smtpUsername;
    }
    public void setSmtpUsername(String smtpUsername) {
        this.smtpUsername = smtpUsername;
    }
    public String getSmtpPassword() {
        return smtpPassword;
    }
    public void setSmtpPassword(String smtpPassword) {
        this.smtpPassword = smtpPassword;
    }
    public String getFromMailAddress() {
        return fromMailAddress;
    }
    public void setFromMailAddress(String fromMailAddress) {
        this.fromMailAddress = fromMailAddress;
    }
    public String getToMailAddress() {
        return toMailAddress;
    }
    public void setToMailAddress(String toMailAddress) {
        this.toMailAddress = toMailAddress;
    }
    
    public void setToMailAddress(List<String> ls){
        StringBuilder sb=new StringBuilder();
        
        for(String s:ls){
            sb.append(s+",");
        }
        
        setToMailAddress(sb.toString());
    }
    
    public String getCcMailAddress() {
        return ccMailAddress;
    }
    public void setCcMailAddress(String ccMailAddress) {
        this.ccMailAddress = ccMailAddress;
    }
    
    public void setCcMailAddress(List<String> ls){
        StringBuilder sb=new StringBuilder();
        
        for(String s:ls){
            sb.append(s+",");
        }
        
        setCcMailAddress(sb.toString());
    }
    
    
    public String getBccMailAddress() {
        return bccMailAddress;
    }
    public void setBccMailAddress(String bccMailAddress) {
        this.bccMailAddress = bccMailAddress;
    }
    
    public void setBccMailAddress(List<String> ls){
        StringBuilder sb=new StringBuilder();
        
        for(String s:ls){
            sb.append(s+",");
        }
        
        setBccMailAddress(sb.toString());
    }
}
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.activation.DataSource;

public class ByteArrayDataSource implements DataSource {

    private final String contentType;
    private final byte[] buf;
    private final int len;

    public ByteArrayDataSource(byte[] buf, String contentType) {
        this(buf, buf.length, contentType);
    }

    public ByteArrayDataSource(byte[] buf, int length, String contentType) {
        this.buf = buf;
        this.len = length;
        this.contentType = contentType;
    }

    public String getContentType() {
        if (contentType == null)
            return "application/octet-stream";
        return contentType;
    }

    public InputStream getInputStream() {
        return new ByteArrayInputStream(buf, 0, len);
    }

    public String getName() {
        return null;
    }

    public OutputStream getOutputStream() {
        throw new UnsupportedOperationException();
    }
}
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
 * Smtp认证
 */
public class SmtpAuthenticator extends Authenticator {
    String username = null;
    String password = null;

    // SMTP身份验证
    public SmtpAuthenticator(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(this.username, this.password);
    }

}

扩展类之一,这个可以作为发送邮件及附件的例子:

public class TestMailSender extends BaseMailService{
    
    public static void main(String[] args) throws Exception{
        TestMailSender s=new TestMailSender();
        
        s.setSmtpServer("D230016.cn.ufo.com");
        s.setSmtpUsername("XXXX");
        s.setSmtpPassword("XXX");
        
        s.setFromMailAddress("nfhep@123.ufo.com");
        s.setToMailAddress("heyng@ufo.com");
        s.setCcMailAddress("");
        s.setBccMailAddress("");
        
        String[] arr=new String[2];
        arr[1]="c://2.xml";
        arr[0]="c://1.xml";
        
        s.sendMail("title","content",arr);    
    }
}

扩展类之二,这个可以作为只发送邮件的例子:

public class RttsMailSender extends BaseMailService{
    public RttsMailSender(){
        super();
        
        this.setSmtpServer("D230016.UFO.com");
        this.setSmtpUsername("1234");
        this.setSmtpPassword("5678");
        
        this.setFromMailAddress("nfelp@ufo.com");
    }
    
    public static void main(String[] args) throws Exception{
        RttsMailSender s=new RttsMailSender();
        s.setToMailAddress("heya@ufo.com");
        s.sendMail("hello", "world");
    }
}