服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

我常用的邮件发送类

package javax.util.zz;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
import java.net.*;
import java.io.*;


/**
 * <p>邮件发送类</p>
 * <p>支持普通模式和html模式,可发送多个附件,支持smtp服务器认证。<br>基于javamail开发,使用时请将javamail包含在classpath系统变量中。</p>
 * <p><br>使用说明:</p>
 * <p>mail mail=new mail();</p>
 * <p>mail.setxxx ....</p>
 * <p>mail.send();<br></p>
 * @author
 * @version 1.0
 */
public class mail {

  private address[] to = null;
  private address[] cc = null;
  private address[] bcc = null;
  private string from = "";
  private string title = "";
  private string content = "";
  private string smtphost = "";
  private int smtpport = 25;
  private string content_type = mode_text;
  private string htmlmaildesc = "";

  private string smtpuser = "";
  private string smtppassword = "";
  private boolean isauthenticationsmtp = false;

  private vector vfiles = new vector();
  private vector vurls = new vector();

  public mail() {
  }

  /**
   * 设置smtp服务器,使用默认端口
   * @param server smtp服务器ip
   */
  public void setsmtphost(string server) {
    this.smtphost = server;
  }

  /**
   * 设置smtp服务器
   * @param server smtp服务器ip
   * @param port 端口
   */
  public void setsmtphost(string server, int port) {
    this.smtphost = server;
    this.smtpport = port;
  }

  /**
   * 设置收件人地址
   * @param aemail 收件人email地址
   */
  public void setto(string aemail) {
    string[] s = new string[1];
    s[0] = aemail;
    this.to = getaddress(s);
  }

  /**
   * 设置多个收件人地址
   * @param emails 收件人email地址
   */
  public void setto(string[] emails) {
    this.to = getaddress(emails);
  }

  /**
   * 设置抄送地址
   * @param aemail 抄送地址
   */
  public void setcc(string aemail) {
    string[] s = new string[1];
    s[0] = aemail;
    this.cc = getaddress(s);
  }

  /**
   * 设置多个抄送地址
   * @param emails 抄送地址
   */
  public void setcc(string[] emails) {
    this.cc = getaddress(emails);
  }

  /**
   * 设置暗送地址
   * @param emails 暗送地址
   */

  public void setbcc(string aemail) {
    string[] s = new string[1];
    s[0] = aemail;
    this.bcc = getaddress(s);
  }

  /**
   * 设置多个暗送地址
   * @param emails 暗送地址
   */
  public void setbcc(string[] emails) {
    this.bcc = getaddress(emails);
  }

  /**
   * 设置发件人地址
   * @param aemail 发件人地址
   */
  public void setfrom(string aemail) {
//        if(!isvalidemailaddress(aemail)){
//            throw new myexception("invalid email address");
//        }
    this.from = aemail;
  }

  /**
   * 设置邮件主题
   * @param mailtitle 邮件主题
   */
  public void setsubject(string mailtitle) {
    this.title = mailtitle;
  }

  /**
   * 设置邮件文字内容
   * @param mailcontent 邮件文字内容
   */
  public void setbody(string mailcontent) {
    this.content = mailcontent;
  }

  /**
   * 设置邮件字符类型
   * @param contenttype 请从静态变量text和html中选择
   */
  public void setcontenttype(string contenttype) {
    this.content_type = contenttype;
  }

  /**
   * 设置html格式邮件在一般模式下显示的说明
   * @param desc 说明文字
   */
  public void sethtmlmaildesc(string desc) {
    this.htmlmaildesc = desc;
  }

  /**
   * 设置smtp服务器用户认证
   * @param username 用户名
   * @param password 密码
   */
  public void setsmtpauthentication(string username, string password) {
    this.smtpuser = username;
    this.smtppassword = password;
    this.isauthenticationsmtp = true;
  }

  /**
   * 添加附件
   * @param afile 本地文件
   */
  public void addattachment(file afile) {
    vfiles.add(afile);
  }

  /**
   * 添加附件
   * @param fileurl 文件url
   */
  public void addattachment(url fileurl) {
    vurls.add(fileurl);
  }

  /**
   * 标示邮件是否附带附件
   * @return
   */
  public boolean hasattachment() {
    return vfiles.size() + vurls.size() > 0;
  }

  /**
   * 发送邮件
   */
  public void send() {
    try {
      properties server = new properties();
      if (stringutil.isempty(this.smtphost)) {
        throw new nullpointerexception("please set smtp host");
      }
      else {
        server.put("mail.smtp.host", this.smtphost);
      }
      server.put("mail.smtp.port", string.valueof(this.smtpport));
      if (this.isauthenticationsmtp) {
        server.put("mail.smtp.auth", "true");
      }
      session conn = session.getinstance(server, null);

      mimemessage msg = new mimemessage(conn);
      if (stringutil.isempty(this.from)) {
        throw new nullpointerexception("please set from address");
      }
      else {
        msg.setfrom(new internetaddress(this.from));
      }
      if (this.to != null) {
        msg.setrecipients(message.recipienttype.to, this.to);
      }
//      else {
//        throw new nullpointerexception("please set to address");
//      }
      if (this.cc != null) {
        msg.setrecipients(message.recipienttype.cc, this.cc);
      }
      if (this.bcc != null) {
        msg.setrecipients(message.recipienttype.bcc, this.bcc);
      }

      sun.misc.base64encoder enc = new sun.misc.base64encoder();
      msg.setsubject("=?gb2312?b?" + enc.encode(this.title.getbytes()) + "?=");

      if (!hasattachment()) {
        //如果没有带附件
        if(this.ishtmlmodemail()){
          //是html格式的邮件
          if (!this.hashtmldesc()) {
            msg.setcontent(this.content, this.content_type);
          }
          else {
            multipart mp = new mimemultipart();
            mimebodypart mbp = null;

            mbp = new mimebodypart();
            mbp.setcontent(this.content, this.content_type);
            mp.addbodypart(mbp);

            mbp = new mimebodypart();
            mbp.setcontent(this.htmlmaildesc, this.mode_text);
            mp.addbodypart(mbp);

            msg.setcontent(mp);
          }
        }
        else{
          //是文本格式的邮件
          msg.settext(this.content);
        }

      }
      else {
        //有附件
        multipart mp = new mimemultipart();
        mimebodypart mbp = null;
        //邮件正文
        for (int i = 0; i < vfiles.size(); i++) {
          mbp = new mimebodypart();
          file file = (file) vfiles.get(i);
          filedatasource fds = new filedatasource(file);
          mbp.setdatahandler(new datahandler(fds));
          mbp.setfilename(stringutil.iso8859_1(file.getname()));
          mp.addbodypart(mbp);
        }
        for (int i = 0; i < vurls.size(); i++) {
          mbp = new mimebodypart();
          url url = (url) vurls.get(i);
//                urldatasource uds=new urldatasource(url);
          mbp.setdatahandler(new datahandler(url));
          mbp.setfilename(stringutil.iso8859_1(url.getfile()));
          mp.addbodypart(mbp);
        }

        mbp = new mimebodypart();
        mbp.setcontent(this.content, this.content_type);
        mp.addbodypart(mbp);

        if (this.ishtmlmodemail() && this.hashtmldesc()) {
          mbp = new mimebodypart();
          mbp.setcontent(this.htmlmaildesc, this.mode_text);
          mp.addbodypart(mbp);
        }

        msg.setcontent(mp);
      }
      msg.savechanges();
      if (this.isauthenticationsmtp) {
        transport transport = conn.gettransport("smtp");
        transport.connect(this.smtphost, this.smtpuser, this.smtppassword);
        transport.sendmessage(msg, msg.getallrecipients());
        transport.close();
      }
      else {
        transport.send(msg, msg.getallrecipients());
      }

    }
    catch (javax.mail.internet.addressexception e) {
      e.printstacktrace();
    }
    catch (javax.mail.messagingexception e) {
      e.printstacktrace();
    }
  }

  public boolean isvalidemailaddress(string email) {
    if (stringutil.isempty(email))
      return false;
    if (email.indexof("@") > 0)
      return !email.endswith("@");
    return false;
  }

  private address[] getaddress(string[] add) {
    address[] a = new address[add.length];
    for (int i = 0; i < add.length; i++) {
      try {
        a[i] = new internetaddress(add[i]);
      }
      catch (addressexception ex) {
        ex.printstacktrace();
      }
    }
    return a;
  }

  public boolean ishtmlmodemail(){
    return this.content_type.equals(this.mode_html);
  }

  public boolean hashtmldesc(){
    if(!this.ishtmlmodemail()) return false;
    return !stringutil.isempty(this.htmlmaildesc);
  }

  /**
   * 普通模式
   */
  public static final string mode_text = "text/plain;charset=gb2312";

  /**
   * html模式
   */
  public static final string mode_html = "text/html;charset=gb2312";
}

扫描关注微信公众号