栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java封装好的mail包发送电子邮件的类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 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 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 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 toList = new ArrayList();
    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 = "test@gmail.com";
List receivers = new ArrayList();
receivers.add("user1@263.com");
receivers.add("user2@263.com");
String content = "邮件主题";
SendMail sendMail = new SendMail();
sendMail.setMailBasicInfo(host, sender, receivers);
sendMail.send(subject, content, null); //没有附件

正文也可以是html内容,如

String content = "详细信息:请点击查看!";

我们再来看一个封装好的类

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;
 

public class EmailServer {
  private static final Logger logger = LoggerFactory.getLogger(EmailServer.class);
  //spring中配置
  
  private List config;
  
  private boolean isDebug = false;
  
  private boolean isAuth = true;
  
  private String authType = "auth";
 
  
  private EmailServer(){}
 
  
  public static EmailServer getInstance(){
    return ApplicationHelper.getInstance().getBean(EmailServer.class);
  }
 
  
  public boolean sendTextMail(String username, String password, String title, String content, String receiver){
    return this.sendTextMail(username, password, title, content, Collections.singletonList(receiver));
  }
 
  
  public boolean sendTextMail(String username, String password, String title, String content, List 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;
    }
  }
 
  
  public boolean sendHtmlMail(String username, String password, String title, String content, String receiver){
    return this.sendHtmlMail(username, password, title, content, Collections.singletonList(receiver));
  }
 
  
  public boolean sendHtmlMail(String username, String password, String title, String content, List 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;
    }
  }
 
  
  private EmailConfig getEmailConfig(String email){
    String mailServiceDomainName = this.getMailServiceDomainName(email);
    for(EmailConfig config : this.config) {
      if(config.getName().equals(mailServiceDomainName)){
 return config;
      }
    }
    return null;
  }
 
  
  private Message makeTextMail(Session session, String title, String content, String from, List 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;
  }
 
  
  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 getConfig() {
    return config;
  }
 
  public void setConfig(List 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 receivers = new ArrayList();
  receivers.add("sunhao0550@163.com");
  receivers.add("sunhao0550@sina.cn");
  EmailServer.getInstance().sendHtmlMail("message_admin@163.com", "这里是密码", "测试发送HTML邮件",
      "测试发送HTML邮件链接到百度", receivers);
  return EmailServer.getInstance().sendTextMail("message_admin@163.com", "这里是密码", "测试发送文本邮件",
      "测试发送文本邮件测试发送文本邮件测试发送文本邮件", receivers);
}

PS:正在考虑扩展,如果把这几个类封在jar包中,如何进行邮件服务器配置的扩展.

如有不好之处,欢迎拍砖.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/150683.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号