爪哇国新游记之三十二----邮件发送

简介:

由三个类完成任务,第一个为主,main中是用法示例。

纯邮件发送和带附件发送邮件皆可,大家请参照main函数中用法。

复制代码
package com.ufo.util.mail;

import java.util.Date;
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;

/**
 * 邮件发送基类
 */
public class BaseMailService{
    protected String smtpServer;
    protected String smtpUsername;
    protected String smtpPassword;
    protected String from;
    protected String to;
    protected String cc;
    protected String bcc;

    /**
     * 无参构造函数
     */
    public BaseMailService(){
        
    }
    
    /**
     * 发送邮件,无附件
     * 
     * @param title
     * @param content
     * @return
     * @throws Exception
     */
    public boolean sendMail(String title,String content) 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(from));// 发件人
        
        // To收件人
        mimeMessage.setRecipients(Message.RecipientType.TO, getInternetAddressArr(to));
        
        // Cc收件人
        InternetAddress[] arr=getInternetAddressArr(cc);
        if(arr!=null && arr.length>0 ){
            mimeMessage.setRecipients(Message.RecipientType.CC, getInternetAddressArr(cc));
        }
        
        // Bcc收件人
        arr=getInternetAddressArr(bcc);
        if(arr!=null && arr.length>0){
            mimeMessage.setRecipients(Message.RecipientType.BCC, getInternetAddressArr(bcc));
        }
        
        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);// 设置邮件内容对象
        
        Transport.send(mimeMessage);// 发送邮件
        
        return true;
    }
    
    /**
     * 发带附件的邮件
     * @param title
     * @param content
     * @param files
     * @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(from));// 发件人
        
        // To收件人
        mimeMessage.setRecipients(Message.RecipientType.TO, getInternetAddressArr(to));
        
        // Cc收件人
        InternetAddress[] arr=getInternetAddressArr(cc);
        if(arr!=null && arr.length>0 ){
            mimeMessage.setRecipients(Message.RecipientType.CC, getInternetAddressArr(cc));
        }
        
        // Bcc收件人
        arr=getInternetAddressArr(bcc);
        if(arr!=null && arr.length>0){
            mimeMessage.setRecipients(Message.RecipientType.BCC, getInternetAddressArr(bcc));
        }
        
        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){
                //添加附件
                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;
        }
        
        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;
    }
    
    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 getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getCc() {
        return cc;
    }

    public void setCc(String cc) {
        this.cc = cc;
    }

    public String getBcc() {
        return bcc;
    }

    public void setBcc(String bcc) {
        this.bcc = bcc;
    }
    
    public static void main(String[] args) throws Exception{
        BaseMailService bms=new BaseMailService();
        
        // 邮件服务器,用户,收发人设置
        bms.setSmtpServer("Ds23M0ds016.cn.ufo.com");
        bms.setSmtpUsername("user");
        bms.setSmtpPassword("password");
        bms.setFrom("adm@us.ufo.com");
        bms.setTo("receiver@cn.ufo.com");
        
        // 邮件标题
        String title ="Hello";
        
        // 邮件正文
        StringBuilder sb = new StringBuilder();
        sb.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
        sb.append("<html>");
        sb.append(" <head>");
        sb.append("  <title> " + title + " </title>");
        sb.append(" </head>");
        sb.append("");
        sb.append(" <body>");
        sb.append("  <h4>Hi:</h4>");
        sb.append("  <p>How are you!. </p>");
        sb.append("  <p>你好</p>");
        sb.append(" </body>");
        sb.append("</html>");
        String content = sb.toString();
        
        String[] files={"c:\\1.xml","c:\\2.xml"};
        
        bms.sendMail(title, content, files);
    }
}

// 辅助类ByteArrayDataSource

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();
    }
}

// 辅助类SmtpAuthenticator
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);
    }

}
复制代码

 












本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/xiandedanteng/p/4184172.html,如需转载请自行联系原作者

相关文章
|
安全 数据安全/隐私保护
最新最全QQ独门使用秘诀
  1、减少qq占用内存资源的秘笈   登陆qq后,占用内存:约8m   qq离线,占用内存:约10m   秘笈:登陆qq后,随便打开一个好友的对话窗口,把它最小化,qq占用的内存就变为3m了,这对于内存小的朋友特别有用!!   2、qq自定义头像上传成功率较高的方法
148 0