刚进公司的training, 下面是要求:

  1. Self-study of Java Mail library:  http://www.oracle.com/technetwork/java/javamail/index.html  --下载Java Mail相关的包
  2. 要求:
    1. (Required)Get attachment (XML) content of current document
    2. by :DynamicEntityModel.toLightXml().  ----转化为字符串
    3. (Optional) Compress the attachment in ZIP format and send as attachment.
    4. package com.core.cbx.coloralbert.action;
      
      import java.io.BufferedOutputStream;
      import java.io.ByteArrayInputStream;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileOutputStream;
      import java.io.FileWriter;
      import java.io.IOException;
      import java.math.BigDecimal;
      import java.util.Properties;
      import java.util.zip.ZipEntry;
      import java.util.zip.ZipOutputStream; import javax.activation.DataHandler;
      import javax.activation.DataSource;
      import javax.activation.FileDataSource;
      import javax.mail.Address;
      import javax.mail.Authenticator;
      import javax.mail.BodyPart;
      import javax.mail.Message;
      import javax.mail.MessagingException;
      import javax.mail.Multipart;
      import javax.mail.PasswordAuthentication;
      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; import org.dom4j.DocumentException;
      import org.dom4j.io.OutputFormat;
      import org.dom4j.io.SAXReader;
      import org.dom4j.io.XMLWriter; import com.core.cbx.action.actionContext.SaveDoc;
      import com.core.cbx.action.exception.ActionException;
      import com.core.cbx.common.type.DateTime;
      import com.core.cbx.data.DynamicEntityModel;
      import com.core.cbx.data.constants.ColorAlbert;
      import com.core.cbx.data.entity.DynamicEntity;
      import com.core.cbx.data.exception.DataException; /**
      * @author Albert.chen
      *
      */
      public class SaveDocAction extends com.core.cbx.action.SaveDocAction<SaveDoc>{ /* (non-Javadoc)
      * @see com.core.cbx.action.SaveDocAction#process(com.core.cbx.action.actionContext.SaveDoc)
      */ @Override
      protected void process(final SaveDoc actionContext) throws ActionException { final DynamicEntity doc = actionContext.getDoc(); //getValue
      final BigDecimal defaultValue = new BigDecimal(0); final BigDecimal rgb_number = doc.getBigDecimal(ColorAlbert.RGB_CODE,defaultValue); final BigDecimal cmyk_number = doc.getBigDecimal(ColorAlbert.CMYK_CODE,defaultValue); final BigDecimal mul_result =rgb_number.multiply(cmyk_number); //setValue
      doc.put(ColorAlbert.HSV_CODE, mul_result); doc.put(ColorAlbert.STATUS, ColorAlbert.WorkflowStatus.IN_PROGRESS); //save information
      super.process(actionContext); } @Override
      protected void postprocess(SaveDoc actionContext) throws ActionException {
      // TODO Auto-generated method stub final DynamicEntity doc = actionContext.getDoc();
      try {
      final String docString=DynamicEntityModel.toLightXml(doc);
      final String refNo=doc.getReference();
      final DateTime updatedOn=doc.getDateTime(ColorAlbert.UPDATED_ON);
      final String updateUser=doc.getString(ColorAlbert.UPDATE_USER);
      final String fileName=strChangeXML(docString,refNo);
      compressedFile(fileName, "D:\\"+ refNo +".zip");
      sengMail(refNo, fileName, updatedOn, updateUser);
      } catch (final DataException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (final IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (final MessagingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (final Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      System.out.println("压缩文件生成失败...");
      } } //将字符串string类型转换成xml文件
      public static String strChangeXML(final String str, final String refNo) throws IOException {
      final SAXReader saxReader = new SAXReader();
      final StringBuffer stringBuffer=new StringBuffer();
      stringBuffer.append(refNo).append(".xml");
      final String fileName=stringBuffer.toString();
      org.dom4j.Document document;
      try {
      document =saxReader.read(new ByteArrayInputStream(str.getBytes("UTF-8")));
      final OutputFormat format = OutputFormat.createPrettyPrint();
      /** 将document中的内容写入文件中 */
      final XMLWriter writer = new XMLWriter(new FileWriter(new File(fileName)),format);
      writer.write(document);
      writer.close();
      } catch (final DocumentException e) {
      e.printStackTrace();
      } return fileName;
      } public static void sengMail( final String refNo,final String fileName, DateTime updatedOn, String updateUser) throws MessagingException{
      // 创建邮件的发送过程中用到的主机和端口号的属性文件
      final Properties pro = new Properties();
      // 设置邮件发送方的主机地址如果是163邮箱,则为smtp.163.com
      // 如果是其他的邮箱可以参照http://wenku.baidu.com/link?url=Cf-1ggeW3e7Rm9KWfz47UL7vvkRpPxAKBlYoTSGpnK4hxpJDiQ0A4lRoPDncMlcMIvUpEn6PD0aObgm5zJaM7AOGkRdccSx6HDH2fSWkxIq这个文档
      pro.put("mail.smtp.host", "*******.com");
      // 设置发送邮件端口号
      pro.put("mail.smtp.port", "25");
      pro.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      // 设置邮件发送需要认证
      pro.put("mail.smtp.auth", "true");
      // 创建邮件验证信息,即发送邮件的用户名和密码
      final Authenticator authenticator = new Authenticator() {
      @Override
      protected PasswordAuthentication getPasswordAuthentication() {
      // 重写验证方法,填写用户名,密码
      return new PasswordAuthentication("*******.com", "ma2s******");
      }
      }; // 根据邮件会话 构建一个邮件的session
      final Session sendMailSession = Session
      .getDefaultInstance(pro, authenticator);
      //打印信息
      sendMailSession.setDebug(true);
      // 创建一个邮件消息
      final Message message = new MimeMessage(sendMailSession);
      // 创建邮件发送者地址
      final Address sourceAddress = new InternetAddress("******.com");
      // 将原地址设置到消息的信息中
      message.setFrom(sourceAddress);
      // 创建邮件的接收者地址
      final Address destAddress = new InternetAddress("***********.com");
      final Address ccAddress=new InternetAddress("************.com");
      // 将接收者的地址设置到消息的信息中
      message.setRecipient(Message.RecipientType.TO, destAddress);
      // 将接收者的地址设置到消息的信息中
      message.setRecipient(Message.RecipientType.CC, ccAddress);
      // 设置邮件的主题
      final StringBuffer strBuf2=new StringBuffer();
      strBuf2.append("subject:").append(refNo).append(".xml ").append("was updatedp[Do Not Reply]");
      message.setSubject(strBuf2.toString()); // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
      final Multipart multipart = new MimeMultipart(); //设置邮件的文本内容
      final BodyPart contentPart = new MimeBodyPart(); final StringBuffer strBuf=new StringBuffer();
      strBuf.append("subject:").append(refNo).append(".xml ").append("was updatedp[Do Not Reply]").append("<br/><br/>");
      strBuf.append("-------------------------------------------------------------").append("<br/>");
      strBuf.append(" Dear Customer,").append("<br/><br/>");
      strBuf.append(refNo).append(" is updated at").append(updatedOn).append(" by ").append(updateUser).append(".").append("<br/><br/>");
      strBuf.append("Regards,").append("<br/>");
      strBuf.append("CBX System").append("<br/>");
      // 设置邮件的发送内容
      contentPart.setContent(strBuf.toString(),"text/html;charset=UTF-8");
      multipart.addBodyPart(contentPart);
      //添加附件
      final BodyPart messageBodyPart= new MimeBodyPart();
      // final String filename="file.txt";
      final DataSource source = new FileDataSource(fileName);
      //添加附件的内容
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); //添加附件2
      final BodyPart messageBodyPart2= new MimeBodyPart();
      final String zipFileName=refNo +".zip";
      final DataSource source2 = new FileDataSource("D:\\"+ zipFileName);
      //添加附件的内容
      messageBodyPart2.setDataHandler(new DataHandler(source));
      messageBodyPart2.setFileName(zipFileName); multipart.addBodyPart(messageBodyPart2); //将multipart对象放到message中
      message.setContent(multipart);
      //保存邮件
      message.saveChanges();
      // 可以设置邮件的发送时间(就是对方看邮件发送的时间)
      // String sendDate = "2013-12-23 17:55:00";
      // Date date = new
      // SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(sendDate);
      // message.setSentDate(date); // 发送邮件
      Transport.send(message);
      } /**
      * @desc 将源文件/文件夹生成指定格式的压缩文件,格式zip
      * @param resourePath 源文件/文件夹
      * @param targetPath 目的压缩文件保存路径
      * @return void
      * @throws Exception
      */
      public void compressedFile(String resourcesPath,String targetPath) throws Exception{
      final File resourcesFile = new File(resourcesPath); //源文件
      final File targetFile = new File(targetPath); //目的
      //如果目的路径不存在,则新建
      if(!targetFile.exists()){
      targetFile.mkdirs();
      } final String targetName = resourcesFile.getName()+".zip"; //目的压缩文件名
      final FileOutputStream outputStream = new FileOutputStream(targetPath+"\\"+targetName);
      final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream)); createCompressedFile(out, resourcesFile, ""); out.close();
      } /**
      * @desc 生成压缩文件。
      * 如果是文件夹,则使用递归,进行文件遍历、压缩
      * 如果是文件,直接压缩
      * @param out 输出流
      * @param file 目标文件
      * @return void
      * @throws Exception
      */
      public void createCompressedFile(ZipOutputStream out,File file,String dir) throws Exception{
      //如果当前的是文件夹,则进行进一步处理
      if(file.isDirectory()){
      //得到文件列表信息
      final File[] files = file.listFiles();
      //将文件夹添加到下一级打包目录
      out.putNextEntry(new ZipEntry(dir+"/")); dir = dir.length() == 0 ? "" : dir +"/"; //循环将文件夹中的文件打包
      for(int i = 0 ; i < files.length ; i++){
      createCompressedFile(out, files[i], dir + files[i].getName()); //递归处理
      }
      }
      else{ //当前的是文件,打包处理
      //文件输入流
      final FileInputStream fis = new FileInputStream(file); out.putNextEntry(new ZipEntry(dir));
      //进行写操作
      int j = 0;
      final byte[] buffer = new byte[1024];
      while((j = fis.read(buffer)) > 0){
      out.write(buffer,0,j);
      }
      //关闭输入流
      fis.close();
      System.out.println("压缩文件已经生成...");
      }
      } }

基于Java Mail 进行发送(带附件和压缩附件)的邮件的更多相关文章

  1. [Java] JavaMail 发送带图片的 html 格式的邮件

    JavaMail 发送的邮件正文和附件是相互独立的,但是内置图片需要定位图片在正文中的位置,所以内置图片和邮件正文是互相依赖的. 发送带附件的邮件可参考JavaMail 发送 html 格式.带附件的 ...

  2. Java网络编程:利用Java mail包发送电子邮件

    下面代码是利用Java mail包封装了一个发送邮件的类 import java.io.File; import java.util.ArrayList; import java.util.Date; ...

  3. 基于java mail实现简单的QQ邮箱发送邮件

    刚学习到java邮件相关的知识,先写下这篇博客,方便以后翻阅学习. -----------------------------第一步 开启SMTP服务 在 QQ 邮箱里的 设置->账户里开启 S ...

  4. UiPath: Send SMTP Mail Message 发送带附件的邮件

    Tips:关于Hotmail的server和port的获取方式,请参考以下链接 https://support.office.com/en-us/article/Server-settings-you ...

  5. 2018.4.28 基于java的聊天系统(带完善)

    Java聊天系统 1.Socket类 Socket(InetAddress address, int port) 创建一个流套接字并将其连接到指定 IP 地址的指定端口号. Socket(String ...

  6. Java Mail多人群发与多附件发送

        近期公司的项目用到了Java Mail来发送注冊邮件,只是.开发的时候都是使用封装好的JAR,曾经也不是非常了解Java Mail的使用原理. 网上非常多代码都是仅仅有一部分,看一看也跑不起来 ...

  7. java mail使用中遇到的550类型错误

    前言 首先,需要说明的是,本错误来自于一个简单的基于java mail的api程序,邮件服务器是163的SMTP,即smtp.163.com. 程序 需要说明一下,下面这个程序,是来自于网络上,本人为 ...

  8. java mail邮件发送(带附件) 支持SSL

    java mail邮件发送(带附件)有三个类 MailSenderInfo.java package mail; import java.util.Properties; import java.ut ...

  9. java发送带附件的邮件

    /** * java发送带附件的邮件 * 周枫 * 2013.8.10 */ package com.dsideal.Util; import javax.mail.*; import javax.m ...

随机推荐

  1. ThinkPHP中的Model模型

    一     实例化模型对象 ①实例化通用模型 例:$goods_model = new \Model\GoodsModel(); $goods_Model = D('Goods'); ②实例化基例模型 ...

  2. Codeforces 890B - Vlad and Cafes Set

    B. Vlad and Cafestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputou ...

  3. PL/SQL简单实现数据库的连接

    通常我们都会去选择 通过修改配置文件去实现数据库链接,方法如下:找到你orale 安装下的文件:instantclient_11_2\network\admin 修改的主要有三个地方:上面的命名随便起 ...

  4. appium测试准备记录

    一 获取应用程序包名(手机中不安装apk) windows 环境下: aapt工具 使用aapt工具,适合给程序自动获取apk的相关信息. //aapt 是sdk自带的一个工具,在SDK/buildt ...

  5. flask_login 整合 pyjwt + json 简易flask框架

    现在很多框架都实现前后端分离,主要为了适应以下几个目的: 1,前后端的分离,可以使前端开发和后端开发更加分工明确,而不是后端还需要在视图模板中加入很多{% XXXX %}标签 2,是为了适应跨域调用或 ...

  6. Java二分法

    public class Dichotomy {        //定义查找次数    static int count = 0;        public static void main(Str ...

  7. JAVA字符串转换MD5值

    简介: MD5即Message-Digest Algorithm 5(信息-摘要算法5),用于确保信息传输完整一致.是计算机广泛使用的杂凑算法之一(又译摘要算法.哈希算法),主流编程语言普遍已有MD5 ...

  8. Android开发中有用工具之--Log工具类

    在开发的过程中.我们常常会使用Log来输出日志,帮助我们来调试程序 可是有时候并不能全然满足我们的须要 ,比方我想知道这个日志信息是来自于哪一个包 哪一个类 所以我们封装一个这个Log类.方便我们的使 ...

  9. 体验CSDN-Markdown

    文件夹 文件夹 文本格式化练习 一号标题 1一号标题 二号标题 1 11 2 列表的应用 链接 图片 脚注 表格 序列图 流程图 文本格式化练习: 斜体 斜体的文字 使用鼠标,变成斜体文字 使用键盘C ...

  10. C#设计模式之二十一职责链模式(Chain of Responsibility Pattern)【行为型】

    一.引言   今天我们开始讲"行为型"设计模式的第八个模式,该模式是[职责链模式],英文名称是:Chain of Responsibility Pattern.让我们看看现实生活中 ...