예제 #1
0
파일: MailEngine.java 프로젝트: yesEric/ws2
  /**
   * Convenience method for sending messages with attachments.
   *
   * @param recipients array of e-mail addresses
   * @param sender e-mail address of sender
   * @param resource attachment from classpath
   * @param bodyText text in e-mail
   * @param subject subject of e-mail
   * @param attachmentName name for attachment
   * @throws MessagingException thrown when can't communicate with SMTP server
   */
  public void sendMessage(
      String[] recipients,
      String sender,
      ClassPathResource resource,
      String bodyText,
      String subject,
      String attachmentName)
      throws MessagingException {
    MimeMessage message = ((JavaMailSenderImpl) mailSender).createMimeMessage();

    // use the true flag to indicate you need a multipart message
    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    helper.setTo(recipients);

    // use the default sending if no sender specified
    if (sender == null) {
      helper.setFrom(defaultFrom);
    } else {
      helper.setFrom(sender);
    }

    helper.setText(bodyText);
    helper.setSubject(subject);

    helper.addAttachment(attachmentName, resource);

    ((JavaMailSenderImpl) mailSender).send(message);
  }
예제 #2
0
  /**
   * 发送邮件
   *
   * @param to 收件人列表
   * @param subject 邮件主题
   * @param text 邮件内容
   * @param files 附件
   * @param personal 私人信息
   * @throws MessagingException 邮件异常信
   */
  public static void sendMail(
      Collection<String> to, String subject, String text, Collection<File> files, String personal)
      throws MessagingException {
    if (to == null || to.size() < 1) {
      logger.error("主题: {} 收件人地址为空", subject);
      throw new MessagingException("主题: [" + subject + "] 收件人地址为空");
    }
    logger.info("开始发送邮件= 收件人:{}, 主题: {}", JSON.toJSONString(to), subject);

    System.setProperty("mail.mime.encodefilename", "true");
    MimeMessage mailMessage = getMailSender().createMimeMessage();
    // 注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,
    // multipart模式 为true时发送附件 可以设置html格式
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

    messageHelper.setTo(to.toArray(new String[to.size()]));
    try {
      messageHelper.setFrom(getMailSender().getUsername(), personal);
    } catch (UnsupportedEncodingException e1) {
      logger.error("发件人邮件格式错误:{}", getMailSender().getUsername());
      throw new MessagingException("发件人邮件格式错误:" + getMailSender().getUsername(), e1);
    }
    messageHelper.setSubject(subject);
    messageHelper.setText(text, true);
    if (files != null) {
      for (File file : files) messageHelper.addAttachment(file.getName(), file);
    }
    doSendMail(mailMessage);
    logger.info("完成发送邮件= 收件人:{}, 主题: {}", JSON.toJSONString(to), subject);
  }
예제 #3
0
  public void sendMail(String plainText, String htmlText, String attachment) {

    MimeMessage message = mailSender.createMimeMessage();
    try {
      MimeMessageHelper helper = new MimeMessageHelper(message, true);
      helper.setFrom(simpleMailMessage.getFrom());
      helper.setTo(simpleMailMessage.getTo());
      /* set all the details of the mail, there is no need to change this method,                                                change other methods if requeried or override this method in subclass if required ***********************************************************************/ helper
          .setBcc("*****@*****.**");
      /* plantext null will not work on plain html*/
      helper.setSubject(simpleMailMessage.getSubject());
      helper.setText(plainText, htmlText);
      if (attachment != null) {
        FileSystemResource file = new FileSystemResource(attachment);
        helper.addAttachment(file.getFilename(), file);
      }
      mailSender.send(message);
    } catch (MessagingException e) {
      System.out.print(e.getMessage());
      logger.error("Exception in Method:sendMail", e);
    } catch (Exception ex) {
      System.out.print(ex.getMessage());
      logger.error("Exception in Method:sendMail", ex);
    }
  }
예제 #4
0
  private void enviaCorreo(String tipo, List<Almacen> almacenes, HttpServletRequest request)
      throws JRException, MessagingException {
    log.debug("Enviando correo {}", tipo);
    byte[] archivo = null;
    String tipoContenido = null;
    switch (tipo) {
      case "PDF":
        archivo = generaPdf(almacenes);
        tipoContenido = "application/pdf";
        break;
      case "CSV":
        archivo = generaCsv(almacenes);
        tipoContenido = "text/csv";
        break;
      case "XLS":
        archivo = generaXls(almacenes);
        tipoContenido = "application/vnd.ms-excel";
    }

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("almacen.lista.label", null, request.getLocale());
    helper.setSubject(
        messageSource.getMessage(
            "envia.correo.titulo.message", new String[] {titulo}, request.getLocale()));
    helper.setText(
        messageSource.getMessage(
            "envia.correo.contenido.message", new String[] {titulo}, request.getLocale()),
        true);
    helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
    mailSender.send(message);
  }
예제 #5
0
  /**
   * 发送邮件
   *
   * @param vo 邮件信息
   * @return
   */
  public boolean send(MailBo vo) {
    boolean isSuccess = false;
    JavaMailSender sender = getMailSenderByVo(vo);
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper;

    String fromName = vo.getFromName();
    String fromAddr = vo.getFrom();
    String subject = vo.getSubject();

    Integer emailType =
        vo.getEmailType() == null ? MailConstants.MAIL_TYPE_SIMPLIFIED : vo.getEmailType();
    String content = freeMarkerHelper.generateContent(vo.getTemplate(), vo.getTemplateMap());
    if (StringUtils.endsWith(fromAddr, "@job5156.com")) { // 已备案通道,取消伪装发送 2014-10-16
      // fromAddr = "chitone" + RandomStringUtils.randomAlphanumeric(4) + "@job5156.com";
    }

    if (emailType.equals(MailConstants.MAIL_TYPE_TRADITIONAL)) {
      /*fromName = FontConvert.gbkToBig5(fromName);
      subject = FontConvert.gbkToBig5(subject);
      content = FontConvert.gbkToBig5(content);*/

      fromName = ChineseCodeChangeUtil.toTraditional(fromName);
      subject = ChineseCodeChangeUtil.toTraditional(subject);
      content = ChineseCodeChangeUtil.toTraditional(content);
    }

    try {
      helper = new MimeMessageHelper(message, true, "UTF-8");
      helper.setFrom(fromAddr, fromName);
      helper.setTo(vo.getTo());
      helper.setSubject(subject);
      helper.setText(content, true);

      // 添加附件到邮件消息中
      MailAttachVo[] attachList = vo.getAttachList();
      if (attachList != null) {
        for (MailAttachVo attach : attachList) {
          if (attach.getFile() == null) continue;
          helper.addAttachment(attach.getAttachName(), attach.getFile());
        }
      }
      // helper.addAttachment();
    } catch (MessagingException | UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    try {
      sender.send(message);
      isSuccess = true;
    } catch (Exception ex) {
      isSuccess = false;
      ex.printStackTrace();
      System.err.println(ex.getMessage());
    }
    return isSuccess;
  }
예제 #6
0
  public void mail(
      String aTo,
      String aSubject,
      String aMessage,
      Map<HeaderType, String> aHeaders,
      Map<String, byte[]> aAttachments)
      throws MessagingException {
    Validate.notEmpty(aTo, "The receiver must be specified.");
    Validate.notEmpty(aSubject, "The subject must be specified.");
    Validate.notEmpty(aMessage, "The message cannot be empty.");

    MimeMessage message = m_MailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    helper.setFrom(m_From);
    helper.setSubject(aSubject);
    helper.setText(aMessage);

    setHelperMethod(addTo, aTo, helper);

    if (aHeaders != null)
      for (HeaderType headerType : aHeaders.keySet()) {
        Validate.notEmpty(
            aHeaders.get(headerType),
            "The value attached to headers key " + headerType + " cannot be empty.");

        if (HeaderType.CC.equals(headerType))
          setHelperMethod(addCC, aHeaders.get(headerType), helper);

        if (HeaderType.BCC.equals(headerType))
          setHelperMethod(addBCC, aHeaders.get(headerType), helper);
      }

    if (aAttachments != null)
      for (String attachmentName : aAttachments.keySet()) {
        Validate.notEmpty(attachmentName, "All attachments must have a non empty name");
        Validate.isTrue(
            aAttachments.get(attachmentName).length > 0,
            "The content of attachment " + attachmentName + " cannot be empty.");

        helper.addAttachment(
            attachmentName, new ByteArrayResource(aAttachments.get(attachmentName)));
      }

    log.info("Sending message " + aSubject + " to " + aTo);

    m_MailSender.send(message);
  }
예제 #7
0
 public void sendEmail(String to, String from, String sub, String msgBody, byte[] content) {
   MimeMessage message = mailSender.createMimeMessage();
   try {
     MimeMessageHelper helper = new MimeMessageHelper(message, true);
     helper.setFrom(from);
     helper.setTo(to);
     helper.setSubject(sub);
     helper.setText(msgBody);
     // 在邮件里的附件的名字
     helper.addAttachment("MyTestFile.txt", new ByteArrayResource(content));
     mailSender.send(message);
   } catch (MessagingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
예제 #8
0
  private void sendThisNcExcel() {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-mail.xml");
    JavaMailSender sender = (JavaMailSender) context.getBean("mailSender");
    try {
      Date date = new Date();
      Calendar cr = Calendar.getInstance();
      cr.setTime(date);
      if (cr.get(Calendar.HOUR_OF_DAY) < 19) {
        cr.add(Calendar.DAY_OF_YEAR, -1);
        date = cr.getTime();
      }

      String sdate = sdf.format(date);

      String filename =
          System.getProperty("user.dir") + "/src/main/resources/nctable_" + sdate + ".xls";

      MimeMessage mimeMess = new JavaMailSenderImpl().createMimeMessage();
      MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMess, true, "utf-8");
      List<InternetAddress> recivers = new ArrayList<>();
      recivers.add(new InternetAddress("*****@*****.**"));
      recivers.add(new InternetAddress("*****@*****.**"));
      recivers.add(new InternetAddress("*****@*****.**"));
      recivers.add(new InternetAddress("*****@*****.**"));

      int num = recivers.size();
      InternetAddress[] sendTo = new InternetAddress[num];
      recivers.toArray(sendTo);
      messageHelper.setTo(sendTo);
      messageHelper.setFrom("*****@*****.**");
      messageHelper.setSubject("牛叉评估" + sdate + "excel表");
      messageHelper.setText(
          "<html><head></head><body> 牛叉评估" + sdate + " 爬取数据见附件</body></html>", true);

      File file = new File(filename);
      messageHelper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
      sender.send(mimeMess);
      log.info("send success");
    } catch (Exception e) {
      log.error(e);
      e.printStackTrace();
    }
  }
예제 #9
0
  /**
   * Convenience method for sending messages with attachments.
   *
   * @param emailAddresses
   * @param resource
   * @param bodyText
   * @param subject
   * @param attachmentName
   * @throws MessagingException
   * @author Ben Gill
   */
  public void sendMessage(
      String[] emailAddresses,
      ClassPathResource resource,
      String bodyText,
      String subject,
      String attachmentName)
      throws MessagingException {
    MimeMessage message = ((JavaMailSenderImpl) mailSender).createMimeMessage();

    // use the true flag to indicate you need a multipart message
    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    helper.setTo(emailAddresses);
    helper.setText(bodyText);
    helper.setSubject(subject);

    helper.addAttachment(attachmentName, resource);

    ((JavaMailSenderImpl) mailSender).send(message);
  }
  @Override
  public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext)
      throws Exception {
    RepeatStatus status = RepeatStatus.CONTINUABLE;

    if (chunkContext.getStepContext().getStepExecution().getReadCount() < resources.length) {
      // On each iteration we add as an attachment a resource
      Resource resource =
          resources[chunkContext.getStepContext().getStepExecution().getReadCount()];

      helper.addAttachment(resource.getFilename(), resource.getFile());
      // We confirm that we read one resource
      contribution.incrementReadCount();
    } else {
      // We send the e-mail on the last iteration
      this.mailSender.send(helper.getMimeMessage());
      // We confirm the number of attachments
      contribution.incrementWriteCount(resources.length);
      status = RepeatStatus.FINISHED;
    }

    return status;
  }
예제 #11
0
  /** 发送MIME格式的用户修改通知邮件. */
  public void sendNotificationMail(String userName) {

    try {
      MimeMessage msg = mailSender.createMimeMessage();
      MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING);

      helper.setTo("*****@*****.**");
      helper.setFrom("*****@*****.**");
      helper.setSubject("用户修改通知");

      String content = generateContent(userName);
      helper.setText(content, true);

      File attachment = generateAttachment();
      helper.addAttachment("mailAttachment.txt", attachment);

      mailSender.send(msg);
      logger.info("HTML版邮件已发送至[email protected]");
    } catch (MessagingException e) {
      logger.error("构造邮件失败", e);
    } catch (Exception e) {
      logger.error("发送邮件失败", e);
    }
  }
  /**
   * Send an email message
   *
   * @throws AlfrescoRuntimeExeption
   */
  @SuppressWarnings("unchecked")
  @Override
  protected void executeImpl(final Action ruleAction, final NodeRef actionedUponNodeRef) {
    try {
      MimeMessage message = javaMailSender.createMimeMessage();
      // use the true flag to indicate you need a multipart message
      MimeMessageHelper helper = new MimeMessageHelper(message, true);

      // set recipient
      String to = (String) ruleAction.getParameterValue(PARAM_TO);
      if (to != null && to.length() != 0) {
        helper.setTo(to);
      } else {
        // see if multiple recipients have been supplied - as a list of
        // authorities
        Serializable toManyMails = ruleAction.getParameterValue(PARAM_TO_MANY);
        List<String> recipients = new ArrayList<String>();
        if (toManyMails instanceof List) {
          for (String mailAdress : (List<String>) toManyMails) {
            if (validateAddress(mailAdress)) {
              recipients.add(mailAdress);
            }
          }
        } else if (toManyMails instanceof String) {
          if (validateAddress((String) toManyMails)) {
            recipients.add((String) toManyMails);
          }
        }
        if (recipients != null && recipients.size() > 0) {
          helper.setTo(recipients.toArray(new String[recipients.size()]));
        } else {
          // No recipients have been specified
          logger.error("No recipient has been specified for the mail action");
        }
      }

      // set subject line
      helper.setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT));

      // See if an email template has been specified
      String text = null;
      NodeRef templateRef = (NodeRef) ruleAction.getParameterValue(PARAM_TEMPLATE);
      if (templateRef != null) {
        // build the email template model
        Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, ruleAction);

        // process the template against the model
        text = templateService.processTemplate("freemarker", templateRef.toString(), model);
      }

      // set the text body of the message
      if (text == null) {
        text = (String) ruleAction.getParameterValue(PARAM_TEXT);
      }
      // adding the boolean true to send as HTML
      helper.setText(text, true);
      FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
      /* add inline images.
       * "action.parameters.images is a ,-delimited string, containing a map of images and resources, from this example:
      message.setText("my text <img src='cid:myLogo'>", true);
      message.addInline("myLogo", new ClassPathResource("img/mylogo.gif"));
      so the "images" param can look like this: headerLogo|images/headerLogoNodeRef,footerLogo|footerLogoNodeRef
       */
      String imageList = (String) ruleAction.getParameterValue(PARAM_IMAGES);
      System.out.println(imageList);
      String[] imageMap = imageList.split(","); // comma no spaces
      Map<String, String> images = new HashMap<String, String>();
      for (String image : imageMap) {
        System.out.println(image);
        String map[] = image.split("\\|");
        for (String key : map) {
          System.out.println(key);
        }

        System.out.println(map.length);

        images.put(map[0].trim(), map[1].trim());
        System.out.println(images.size());
        System.out.println("-" + map[0] + " " + map[1] + "-");
      }
      NodeRef imagesFolderNodeRef = (NodeRef) ruleAction.getParameterValue(PARAM_IMAGES_FOLDER);
      if (null != imagesFolderNodeRef) {
        ContentService contentService = serviceRegistry.getContentService();
        System.out.println("mapping");
        for (Map.Entry<String, String> entry : images.entrySet()) {
          System.out.println(
              entry.getKey()
                  + " "
                  + entry.getValue()
                  + " "
                  + ruleAction.getParameterValue(PARAM_IMAGES_FOLDER));
          NodeRef imageFile = fileFolderService.searchSimple(imagesFolderNodeRef, entry.getValue());
          if (null != imageFile) {
            ContentReader reader = contentService.getReader(imageFile, ContentModel.PROP_CONTENT);
            ByteArrayResource resource =
                new ByteArrayResource(IOUtils.toByteArray(reader.getContentInputStream()));
            helper.addInline(entry.getKey(), resource, reader.getMimetype());

          } else {
            logger.error("No image for " + entry.getKey());
          }
        }
      } else {
        logger.error("No images folder");
      }

      // set the from address
      NodeRef person = personService.getPerson(authService.getCurrentUserName());

      String fromActualUser = null;
      if (person != null) {
        fromActualUser = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL);
      }
      if (fromActualUser != null && fromActualUser.length() != 0) {
        helper.setFrom(fromActualUser);
      } else {
        String from = (String) ruleAction.getParameterValue(PARAM_FROM);
        if (from == null || from.length() == 0) {
          helper.setFrom(fromAddress);
        } else {
          helper.setFrom(from);
        }
      }
      NodeRef attachmentsFolder = (NodeRef) ruleAction.getParameterValue(PARAM_ATTCHMENTS_FOLDER);
      if (attachmentsFolder != null) {

        List<FileInfo> attachFiles = fileFolderService.listFiles(attachmentsFolder);
        if (attachFiles != null && attachFiles.size() > 0) {
          for (FileInfo attachFile : attachFiles) {
            ContentReader contentReader = fileFolderService.getReader(attachFile.getNodeRef());
            ByteArrayResource resource =
                new ByteArrayResource(IOUtils.toByteArray(contentReader.getContentInputStream()));
            helper.addAttachment(attachFile.getName(), resource, contentReader.getMimetype());
          }
        }
      }

      // Send the message unless we are in "testMode"
      javaMailSender.send(message);
    } catch (Exception e) {
      String toUser = (String) ruleAction.getParameterValue(PARAM_TO);
      if (toUser == null) {
        Object obj = ruleAction.getParameterValue(PARAM_TO_MANY);
        if (obj != null) {
          toUser = obj.toString();
        }
      }

      logger.error("Failed to send email to " + toUser, e);

      throw new AlfrescoRuntimeException("Failed to send email to:" + toUser, e);
    }
  }
 /**
  * 发送邮件
  *
  * @param senderTitle 发送人名称,
  * @param senderMail 发送人邮箱地址,
  * @param userTitles 收件人名称列表,
  * @param userMails 收件人邮件地址列表,
  * @param mailCCs 抄送列表,
  * @param subject 邮件标题,
  * @param content 邮件内容,
  * @param isHtml 邮件内容是否为HTML格式
  * @param fileTable
  * @throws MessagingException
  * @throws UnsupportedEncodingException
  */
 private void send(
     String senderTitle,
     String senderMail,
     String[] userTitles,
     String[] userMails,
     String[] mailCCs,
     String[] mailBCCs,
     String subject,
     String content,
     boolean isHtml,
     Hashtable<String, File> fileTable)
     throws MessagingException, UnsupportedEncodingException {
   /*
    * if send mail is disabled, then return from this method.
    */
   if (!active) return;
   // ------------------------------------------------------------------------------------------------------------------------------------------
   MimeMessage message = mailSender.createMimeMessage();
   MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true, DEFAULT_ENCODING);
   // ------------------------------------------------------------------------------------------------------------------------------------------
   if (senderMail != null) {
     if (senderTitle != null) {
       mimeMessageHelper.setFrom(senderMail, senderTitle);
     } else {
       mimeMessageHelper.setFrom(senderMail);
     }
   }
   // ------------------------------------------------------------------------------------------------------------------------------------------
   if (StringUtil.isEmpty(mailTo)) {
     if (userMails != null) {
       if (userTitles == null) {
         mimeMessageHelper.setTo(userMails);
       } else {
         for (int i = 0; i < userMails.length; i++) {
           if (i > userTitles.length || userTitles.length == 0) {
             mimeMessageHelper.addTo(userMails[i]);
           } else {
             mimeMessageHelper.addTo(userMails[i], userTitles[i]);
           }
         }
       }
     }
     if (mailCCs != null) mimeMessageHelper.setCc(mailCCs);
     if (mailBCCs != null) mimeMessageHelper.setBcc(mailBCCs);
   } else {
     if (log.isDebugEnabled()) {
       log.debug(
           "Option 'MailTo' is settled, mail '" + subject + "' will be sent to '" + mailTo + "'.");
     }
     mimeMessageHelper.addTo(mailTo);
   }
   // ------------------------------------------------------------------------------------------------------------------------------------------
   if (subject != null) mimeMessageHelper.setSubject(subject);
   if (content != null) mimeMessageHelper.setText(content, isHtml);
   if (fileTable != null) {
     Enumeration<String> e = fileTable.keys();
     while (e.hasMoreElements()) {
       String key = e.nextElement();
       File file = fileTable.get(key);
       mimeMessageHelper.addAttachment(key, file);
     }
   }
   mailSender.send(mimeMessageHelper.getMimeMessage());
   // ------------------------------------------------------------------------------------------------------------------------------------------
   message = null;
   mimeMessageHelper = null;
 }