刚进公司的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. zzuli 1812: sort 排序

    1812: sort Time Limit: 1 Sec  Memory Limit: 128 MB Submit: 352  Solved: 216 SubmitStatusWeb Board De ...

  2. php面试之四-Linux部分

    php面试题之四——Linux部分(高级部分) 四.Linux部分 1.请解释下列10个shell命令的用途(新浪网技术部) top.ps.mv.find.df.cat.chmod.chgrp.gre ...

  3. Python处理json字符串转化为字典

    有一个需求,需要用python把json字符串转化为字典 inp_str = " {'k1':123, 'k2': '345','k3','ares'} " import json ...

  4. SAML2.0 协议初识(一)

    一.什么是 SAML 协议? SAML 即安全断言标记语言,英文全称是 Security Assertion Markup Language.它是一个基于 XML 的标准,用于在不同的安全域(secu ...

  5. iOS_应用程序的生命周期

    每个iPhone程序都包括唯一一个UIApplication对象,它管理整个程序的生命周期,从载入第一个显示界面開始,而且监听系统事件.程序事件调度整个程序的运行. int main(int argc ...

  6. freemarker四种变量

    freemarker四种变量 1.简单介绍说明 (1)数据模型中的变量:root中的变量 (2)模板中的变量:使用<#assign>定义的变量 (3)局部变量:在指令中的变量 (4)循环变 ...

  7. 【剑指offer】扑克牌的顺子

    个大王,2个小王(一副牌原本是54张^_^)...他随机从中抽出了5张牌,想測測自己的手气,看看能不能抽到顺子,假设抽到的话,他决定去买体育彩票,嘿嘿! ."红心A,黑桃3,小王,大王,方片 ...

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

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

  9. AspNet Core Api Restful +Swagger 实现微服务之旅(四)

    这几天没更新,项目框架也是在发展阶段,这几天学习配置了一遍Apollo和RabbitMQ 等到放到框架上之后我整理一下到时候把心得写出来相互学习. 接着上一篇的内容 (2)  程序错误时  返回数据格 ...

  10. 自学Python4.2 迭代器、生成器

    迭代器.生成器一.迭代器 迭代器是访问集合元素的一种方式.迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束.迭代器只能往前不会后退,不过这也没什么, 因为人们很少在迭代途中往后退.另外 ...