程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java封裝好的mail包發送電子郵件的類

Java封裝好的mail包發送電子郵件的類

編輯:關於JAVA

Java封裝好的mail包發送電子郵件的類。本站提示廣大學習愛好者:(Java封裝好的mail包發送電子郵件的類)文章只能為提供參考,不一定能成為您想要的結果。以下是Java封裝好的mail包發送電子郵件的類正文


上面代碼是應用Java mail包封裝了一個發送郵件的類

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

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

public class SendMail {
  private static final String MAIL_ADDRESS_REGEX = "^[\\w\\.=-]+@[\\w\\.-]+\\.[\\w]{2,3}$";

  private String mailServer;
  private String sender;
  private String[] receiver;

  public SendMail(){

  }

  public void setMailBasicInfo(String mailServer,String sender,String receiver){
    this.mailServer = mailServer;
    this.sender = sender;
    this.receiver =receiver.split(",");
  }

  public void setMailBasicInfo(String mailServer,String sender,String[] users){
    this.mailServer = mailServer;
    this.sender = sender;
    this.receiver = users;
  }

  public void setMailBasicInfo(String mailServer,String sender,List<String> users){
    this.mailServer = mailServer;
    this.sender = sender;
    this.receiver = new String[users.size()];
    users.toArray(this.receiver);
  }

  public boolean send(String subject, String content, List<String> fileNames)
  {
    subject = subject==null?"":subject;
    content = content==null?"":content;
    Properties props = new Properties();
    props.put("mail.smtp.host", mailServer);
    Session session = Session.getInstance(props, null);
    try
    {
      InternetAddress[] receiver = getReceiverList();
      if (receiver.length == 0)
      {
        System.out.println("receiver is null");
        return false;
      }
      MimeMessage msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(sender));
      msg.setRecipients(Message.RecipientType.TO, receiver);
      msg.setSubject(subject);
      msg.setSentDate(new Date());

      Multipart container = new MimeMultipart();
      MimeBodyPart textBodyPart = new MimeBodyPart();
      textBodyPart.setContent(content.toString(), "text/html;charset=gbk");
      container.addBodyPart(textBodyPart);

      doAttachFile(container,fileNames);
      msg.setContent(container);
      System.out.println("begin send mail");
      Transport.send(msg);
      System.out.println("send mail success");
    }
    catch (MessagingException e)
    {
      System.out.println("send mail fail");
      System.out.println(e);
      return false;
    }
    catch(Exception e){
      return false;
    }
    return true;
  }

  public boolean send(String subject, String content){
    return send(subject,content,null);
  }

  public boolean send(String subject){
    return send(subject,null);
  }

  private void doAttachFile(Multipart container, List<String> fileNames) throws MessagingException{
    if(fileNames==null || fileNames.size()==0)
      return;
    for(String filename:fileNames){
      File f = new File(filename);
      if(!f.isFile())
        continue;
      System.out.println("the attach file is:"+filename);
      MimeBodyPart fileBodyPart = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(f);// 要發送的附件地址
      fileBodyPart.setDataHandler(new DataHandler(fds));
      fileBodyPart.setFileName(fds.getName());// 設置附件的稱號
      container.addBodyPart(fileBodyPart);
    }
  }

  private InternetAddress[] getReceiverList() throws AddressException
  {
    ArrayList<InternetAddress> toList = new ArrayList<InternetAddress>();
    for (int i = 0; i < receiver.length; ++i)
    {
      if (receiver[i].matches(MAIL_ADDRESS_REGEX))
      {
        toList.add(new InternetAddress(receiver[i]));
      }
    }

    return (InternetAddress[]) toList.toArray(new InternetAddress[toList.size()]);
  }
}

應用舉例

String host = "168.xx.xx.xx"; //郵件辦事器的地址
String subject = "發送郵件的主題";
String sender = "[email protected]";
List<String> receivers = new ArrayList<String>();
receivers.add("[email protected]");
receivers.add("[email protected]");
String content = "郵件主題";
SendMail sendMail = new SendMail();
sendMail.setMailBasicInfo(host, sender, receivers);
sendMail.send(subject, content, null); //沒有附件

注釋也能夠是html內容,如

String content = "<html>具體信息:<a href='xxxx'>請點擊檢查!</a></html>";

我們再來看一個封裝好的類

package com.message.base.email;
 
import com.message.base.spring.ApplicationHelper;
import com.message.base.utils.StringUtils;
import com.message.base.utils.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;
 
/**
 * 發送郵件辦事器.
 *
 * @author sunhao([email protected])
 * @version V1.0, 13-3-25 上午6:19
 */
public class EmailServer {
  private static final Logger logger = LoggerFactory.getLogger(EmailServer.class);
  //spring中設置裝備擺設
  /**郵箱辦事器設置裝備擺設**/
  private List<EmailConfig> config;
  /**能否開啟debug調試形式**/
  private boolean isDebug = false;
  /**能否啟用身份驗證**/
  private boolean isAuth = true;
  /**驗證類型**/
  private String authType = "auth";
 
  /**
   * 公有化默許結構器,使內部弗成實例化
   */
  private EmailServer(){}
 
  /**
   * 單例,包管高低文中只要一個EmailServer
   *
   * @return EmailServer
   */
  public static EmailServer getInstance(){
    return ApplicationHelper.getInstance().getBean(EmailServer.class);
  }
 
  /**
   * 發送通俗郵件(單個吸收人)
   *
   * @param username   發件人用戶名
   * @param password   發件人暗碼
   * @param title     郵件題目
   * @param content    郵件注釋
   * @param receiver   單個吸收人
   * @return
   */
  public boolean sendTextMail(String username, String password, String title, String content, String receiver){
    return this.sendTextMail(username, password, title, content, Collections.singletonList(receiver));
  }
 
  /**
   * 發送通俗郵件(多個吸收人)
   *
   * @param username   發件人用戶名
   * @param password   發件人暗碼
   * @param title     郵件題目
   * @param content    郵件注釋
   * @param receivers   多個吸收人
   * @return
   */
  public boolean sendTextMail(String username, String password, String title, String content, List<String> receivers){
    Authentication auth = null;
    if(this.isAuth()){
      //假如須要身份認證,則創立一個暗碼驗證器
      auth = new Authentication(username, password);
    }
 
    Properties props = new Properties();
    props.setProperty("mail.smtp.auth", this.isAuth() ? "true" : "false");
    props.setProperty("mail.transport.protocol", "auth");
    EmailConfig config = this.getEmailConfig(username);
    props.setProperty("mail.smtp.host", config.getSmtp());
    props.setProperty("mail.smtp.port", config.getPort() + "");
 
    // 依據郵件會話屬性和暗碼驗證器結構一個發送郵件的session
    Session session = Session.getDefaultInstance(props, auth);
    session.setDebug(this.isDebug);
 
    Message message = this.makeTextMail(session, title, content, username, receivers, false);
    try {
      Transport.send(message);
 
      return true;
    } catch (MessagingException e) {
      logger.error(e.getMessage(), e);
      return false;
    }
  }
 
  /**
   * 發送HTML郵件(單個吸收人)
   *
   * @param username   發件人用戶名
   * @param password   發件人暗碼
   * @param title     郵件題目
   * @param content    郵件注釋
   * @param receiver   單個吸收人
   * @return
   */
  public boolean sendHtmlMail(String username, String password, String title, String content, String receiver){
    return this.sendHtmlMail(username, password, title, content, Collections.singletonList(receiver));
  }
 
  /**
   * 發送HTML郵件(多個吸收人)
   *
   * @param username   發件人用戶名
   * @param password   發件人暗碼
   * @param title     郵件題目
   * @param content    郵件注釋
   * @param receivers   多個吸收人
   * @return
   */
  public boolean sendHtmlMail(String username, String password, String title, String content, List<String> receivers){
    Authentication auth = null;
    if(this.isAuth()){
      //假如須要身份認證,則創立一個暗碼驗證器
      auth = new Authentication(username, password);
    }
 
    Properties props = new Properties();
    props.setProperty("mail.smtp.auth", this.isAuth() ? "true" : "false");
    props.setProperty("mail.transport.protocol", "auth");
    EmailConfig config = this.getEmailConfig(username);
    props.setProperty("mail.smtp.host", config.getSmtp());
    props.setProperty("mail.smtp.port", config.getPort() + "");
 
    // 依據郵件會話屬性和暗碼驗證器結構一個發送郵件的session
    Session session = Session.getDefaultInstance(props, auth);
    session.setDebug(this.isDebug);
 
    Message message = this.makeTextMail(session, title, content, username, receivers, true);
    try {
      Transport.send(message);
 
      return true;
    } catch (MessagingException e) {
      logger.error(e.getMessage(), e);
      return false;
    }
  }
 
  /**
   * 獲得郵件辦事器設置裝備擺設
   *
   * @param email     郵箱地址
   * @return
   */
  private EmailConfig getEmailConfig(String email){
    String mailServiceDomainName = this.getMailServiceDomainName(email);
    for(EmailConfig config : this.config) {
      if(config.getName().equals(mailServiceDomainName)){
        return config;
      }
    }
    return null;
  }
 
  /**
   * 創立郵件message
   *
   * @param session    依據設置裝備擺設取得的session
   * @param title     郵件主題
   * @param content    郵件的內容
   * @param from     發件者
   * @param receivers   收件者
   * @param isHtmlMail  能否是html郵件
   */
  private Message makeTextMail(Session session, String title, String content, String from, List<String> receivers, boolean isHtmlMail){
    Message message = new MimeMessage(session);
    try {
      /**題目**/
      logger.info("this mail's title is {}", title);
      message.setSubject(title);
      /**內容**/
      logger.info("this mail's content is {}", content);
      if(isHtmlMail){
        //是html郵件
        message.setContent(content, "text/html;charset=utf-8");
      } else {
        //通俗郵件
        message.setText(content);
      }
      /**發件者地址**/
      logger.info("this mail's sender is {}", from);
      Address fromAddress = new InternetAddress(from);
      message.setFrom(fromAddress);
      /**吸收者地址**/
      Address[] tos = new InternetAddress[receivers.size()];
      for(int i = 0; i < receivers.size(); i++){
        String receiver = receivers.get(i);
        if(ValidateUtils.isEmail(receiver)){
          tos[i] = new InternetAddress(receiver);
        }
      }
      /**發件時光**/
      message.setSentDate(new Date());
 
      message.setRecipients(Message.RecipientType.TO, tos);
    } catch (MessagingException e) {
      logger.error(e.getMessage(), e);
      e.printStackTrace();
    }
 
    return message;
  }
 
  /**
   * 獲得郵箱域名
   *
   * @param email   郵箱
   * @return
   */
  private String getMailServiceDomainName(String email){
    if(StringUtils.isEmpty(email)){
      return "";
    } else {
      int firstIndex = StringUtils.indexOf(email, "@");
      int secondIndex = StringUtils.lastIndexOf(email, ".");
 
      return StringUtils.substring(email, firstIndex + 1, secondIndex);
    }
  }
 
  public List<EmailConfig> getConfig() {
    return config;
  }
 
  public void setConfig(List<EmailConfig> config) {
    this.config = config;
  }
 
  public boolean isDebug() {
    return isDebug;
  }
 
  public void setDebug(boolean debug) {
    isDebug = debug;
  }
 
  public boolean isAuth() {
    return isAuth;
  }
 
  public void setAuth(boolean auth) {
    isAuth = auth;
  }
 
  public String getAuthType() {
    return authType;
  }
 
  public void setAuthType(String authType) {
    this.authType = authType;
  }
}

挪用方法以下

public boolean sendMail() throws Exception {
  List<String> receivers = new ArrayList<String>();
  receivers.add("[email protected]");
  receivers.add("[email protected]");
  EmailServer.getInstance().sendHtmlMail("[email protected]", "這裡是暗碼", "測試發送HTML郵件",
      "<span style='color: red;font-size: 20pt'>測試發送HTML郵件</span><a href='http://www.百度.com' target='_blank'>鏈接到百度</a>", receivers);
  return EmailServer.getInstance().sendTextMail("[email protected]", "這裡是暗碼", "測試發送文本郵件",
      "測試發送文本郵件測試發送文本郵件測試發送文本郵件", receivers);
}

PS:正在斟酌擴大,假如把這幾個類封在jar包中,若何停止郵件辦事器設置裝備擺設的擴大.

若有欠好的地方,迎接拍磚.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved