欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring框架JavaMailSender发送邮件工具类详解

程序员文章站 2024-02-23 22:17:40
本文实例为大家分享了spring框架javamailsender发送邮件工具类,供大家参考,具体内容如下 需要用到的jar包: 下面是发送工具类代码: p...

本文实例为大家分享了spring框架javamailsender发送邮件工具类,供大家参考,具体内容如下

需要用到的jar包:

Spring框架JavaMailSender发送邮件工具类详解

下面是发送工具类代码:

package com.test.email;

import org.springframework.core.io.filesystemresource;
import org.springframework.mail.simplemailmessage;
import org.springframework.mail.javamail.javamailsenderimpl;
import org.springframework.mail.javamail.mimemessagehelper;

import javax.activation.datahandler;
import javax.activation.filedatasource;
import javax.mail.bodypart;
import javax.mail.message;
import javax.mail.messagingexception;
import javax.mail.multipart;
import javax.mail.internet.internetaddress;
import javax.mail.internet.mimebodypart;
import javax.mail.internet.mimemessage;
import javax.mail.internet.mimemultipart;
import javax.mail.internet.mimeutility;

import java.util.arraylist;
import java.util.hashmap;
import java.util.list;
import java.util.map;
import java.util.properties;

/**
 * @author tlimited
 * @create 2017-08-17 11:38
 **/
public class sendmailutils {

  // spring的邮件工具类,实现了mailsender和javamailsender接口
  private javamailsenderimpl mailsender;

  /**
   * 初始化邮件发送数据
   * @param host 服务器
   * @param username 发送人
   * @param passwd 发送人密码
   */
  public void setinitdata(string host,string username,string passwd){
     //创建邮件发送服务器
    mailsender = new javamailsenderimpl();
    mailsender.sethost(host);
   // mailsender.setport(465);
    mailsender.setusername(username);
    mailsender.setpassword(passwd);
    //加认证机制
    properties javamailproperties = new properties();
    javamailproperties.put("mail.smtp.auth", true);
    javamailproperties.put("mail.smtp.starttls.enable", true);
    javamailproperties.put("mail.smtp.timeout", 5000);
    mailsender.setjavamailproperties(javamailproperties);
    system.out.println("初始化邮件发送信息完成");
  }
  /**
   * 发送普通文本
   * @param email 对方邮箱地址
   * @param subject 主题
   * @param text 邮件内容
   */
  public void simplemailsend(string email,string subject,string text) {
    //创建邮件内容
    simplemailmessage message=new simplemailmessage();
    message.setfrom(mailsender.getusername());
    message.setto(email);
    message.setsubject(subject);
    message.settext(text);
    //发送邮件
    mailsender.send(message);
    system.out.println("发送成功");
  }

  /**
   * 发送附件,支持多附件
   * //使用javamail的mimemessage,支付更加复杂的邮件格式和内容
    //mimemessages为复杂邮件模板,支持文本、附件、html、图片等。
   * @param email 对方邮箱
   * @param subject 主题
   * @param text 内容
   * @param paths 附件路径,和文件名
   * @throws messagingexception
   */
  public void attachedsend(string email,string subject,string text,map<string,string> paths) throws messagingexception {

    mimemessage message = mailsender.createmimemessage();
    //创建mimemessagehelper对象,处理mimemessage的辅助类
    mimemessagehelper helper = new mimemessagehelper(message, true);
    //使用辅助类mimemessage设定参数
    helper.setfrom(mailsender.getusername());
    helper.setto(email);
    helper.setsubject(subject);
    helper.settext(text);

    if (paths!=null){
      paths.foreach((k,v)->{
         //加载文件资源,作为附件
         filesystemresource file = new filesystemresource(v);
         try {
          //添加附件
           helper.addattachment(k, file);
        } catch (exception e) {
          e.printstacktrace();
        }
      });
    }
    //发送邮件
    mailsender.send(message);
    system.out.println("发送成功");
  }

  /**
  * 发送html文件,支持多图片
  * @param email 对方邮箱
  * @param subject 主题
  * @param text 内容
  * @param paths 富文本中添加用到的路径,一般是图片,或者css,js文件
  * @throws messagingexception
  */
  public void richcontentsend(string email,string subject,string text,map<string,string> paths) throws messagingexception {

    mimemessage message = mailsender.createmimemessage();
    mimemessagehelper helper = new mimemessagehelper(message, true);

    helper.setfrom(mailsender.getusername());
    helper.setto(email);
    helper.setsubject(subject);
    //第二个参数true,表示text的内容为html,然后注意<img/>标签,src='cid:file','cid'是contentid的缩写,'file'是一个标记,
    //需要在后面的代码中调用mimemessagehelper的addinline方法替代成文件
    helper.settext(text,true);
    //文件地址相对应src目录
    // classpathresource file = new classpathresource("logo.png");

    if (paths!=null){
      paths.foreach((k,v)->{
         //文件地址对应系统目录
         filesystemresource file = new filesystemresource(v);
         try {
          helper.addinline(k, file);
        } catch (exception e) {
          e.printstacktrace();
        }
      });
    }
    mailsender.send(message);
    system.out.println("发送成功");
  }

  /**
   * 群发多人,且多附件
   * @param mailto 多人邮件地址
   * @param subject 主题
   * @param text 内容
   * @param filepath 文件路径
   * @throws exception
   */
  public void sendbatchmailwithfile(string[] emails, string subject, string text, string[] filepath) throws exception { 

    mimemessage mimemessage = mailsender.createmimemessage(); 
    mimemessagehelper messagehelper = new mimemessagehelper(mimemessage, true, "utf-8"); 
    messagehelper.setfrom(new internetaddress(mimeutility.encodetext(mailsender.getusername()))); 
    messagehelper.setsubject(subject); 
    if (filepath != null) { 
      bodypart mdp = new mimebodypart();// 新建一个存放信件内容的bodypart对象 
      mdp.setcontent(text, "text/html;charset=utf-8");// 给bodypart对象设置内容和格式/编码方式 
      multipart mm = new mimemultipart();// 新建一个mimemultipart对象用来存放bodypart对象 
      mm.addbodypart(mdp);// 将bodypart加入到mimemultipart对象中(可以加入多个bodypart) 
      // 把mm作为消息对象的内容 
      mimebodypart filepart; 
      filedatasource filedatasource; 
      // 逐个加入附件 
      for (int j = 0; j < filepath.length; j++) { 
        filepart = new mimebodypart(); 
        filedatasource = new filedatasource(filepath[j]); 
        filepart.setdatahandler(new datahandler(filedatasource)); 
        try { 
          filepart.setfilename(mimeutility.encodetext(filedatasource.getname())); 
        } catch (exception e) { 
          e.printstacktrace(); 
        } 
        mm.addbodypart(filepart); 
      } 
      mimemessage.setcontent(mm); 
    } else { 
      messagehelper.settext(text, true); 
    } 

    list<internetaddress> list = new arraylist<internetaddress>();// 不能使用string类型的类型,这样只能发送一个收件人 
    for (int i = 0; i < emails.length; i++) { 
      list.add(new internetaddress(emails[i])); 
    } 
    internetaddress[] address = list.toarray(new internetaddress[list.size()]); 

    mimemessage.setrecipients(message.recipienttype.to, address); 
    mimemessage = messagehelper.getmimemessage(); 

    mailsender.send(mimemessage);  
    system.out.println("发送成功");
  } 


  public static void main(string[] args) throws exception
  {
    sendmailutils test = new sendmailutils();
    //测试发送普通文本
   // test.setinitdata("smtp.qq.com","706548532@qq.com","123456");
    test.setinitdata("smtp.163.com","1234@163.com","1234");
    test.simplemailsend("1326624701@qq.com","测试","测试能不能发邮件!!!");

    //测试发送附件
    /* test.setinitdata("smtp.163.com","1234@163.com","1234");
    map<string,string> map = new hashmap<string, string>();
    map.put("test12.xls", "d:\\tomcat8\\apache-tomcat-8.0.29\\test12.xls");
    map.put("wsdl.rar", "d:\\wsdl.rar");
    test.attachedsend("706548532@qq.com","hello attachment","this is a mail with attachment",map);
    */

    //测试发送富文本(html文件)
   /* test.setinitdata("smtp.163.com","1234@163.com","1234");
    string text = "<body><p style='color:red;'>hello html email</p><img src='cid:file'/></body>";
    map<string,string> map = new hashmap<string, string>();
    map.put("file", "e:\\1f7827.jpg");
    test.richcontentsend("706548532@qq.com","邮件标题",text,map);*/

    //测试群发多人多附件
    test.setinitdata("smtp.163.com","1234@163.com","1234");
    string [] address = {"706548532@qq.com","1326624701@qq.com"};
    string [] filepath = {"d:\\tomcat8\\apache-tomcat-8.0.29\\test12.xls", "d:\\wsdl.rar"};
    test.sendbatchmailwithfile(address, "群发多文件", "实时", filepath);
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。