Exemple #1
0
  /**
   * 构建邮件的正文和附件
   *
   * @param msgContent
   * @param attachedFileList
   * @return
   * @throws javax.mail.MessagingException
   * @throws java.io.UnsupportedEncodingException
   */
  public static Multipart buildMimeMultipart(String msgContent, Vector<String> attachedFileList)
      throws MessagingException, UnsupportedEncodingException {
    Multipart mPart = new MimeMultipart(); // 多部分实现

    // 邮件正文
    MimeBodyPart mBodyContent = new MimeBodyPart(); // MIME邮件段体
    if (msgContent != null) {
      mBodyContent.setContent(msgContent, messageContentMimeType);
    } else {
      mBodyContent.setContent("", messageContentMimeType);
    }
    mPart.addBodyPart(mBodyContent);

    // 附件
    String file;
    String fileName;
    if (attachedFileList != null) {
      for (Enumeration<String> fileList = attachedFileList.elements();
          fileList.hasMoreElements(); ) {
        file = fileList.nextElement();
        fileName = file.substring(file.lastIndexOf("/") + 1);
        MimeBodyPart mBodyPart = new MimeBodyPart();
        // 远程资源
        // URLDataSource uds=new
        // URLDataSource(http://www.iteye.com/logo.gif);
        FileDataSource fds = new FileDataSource(file);
        mBodyPart.setDataHandler(new DataHandler(fds));
        // mBodyPart.setFileName(fileName);
        mBodyPart.setFileName(MimeUtility.encodeWord(fileName)); // 解决中文附件名问题
        mPart.addBodyPart(mBodyPart);
      }
    }

    return mPart;
  }
Exemple #2
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();
    }
  }
  @Test
  public void testUTF8() throws Exception {
    envVars.put("EMAIL_LIST", "[email protected], cc:[email protected], 愛嬋 <*****@*****.**>");

    Set<InternetAddress> internetAddresses =
        emailRecipientUtils.convertRecipientString("$EMAIL_LIST", envVars);
    assertEquals(2, internetAddresses.size());

    assertTrue(internetAddresses.contains(new InternetAddress("*****@*****.**")));
    InternetAddress addr = new InternetAddress("*****@*****.**");
    addr.setPersonal(MimeUtility.encodeWord("愛嬋", "UTF-8", "B"));
    assertTrue(internetAddresses.contains(addr));

    internetAddresses =
        emailRecipientUtils.convertRecipientString("$EMAIL_LIST", envVars, EmailRecipientUtils.CC);

    assertEquals(1, internetAddresses.size());
    assertTrue(internetAddresses.contains(new InternetAddress("*****@*****.**")));
  }
Exemple #4
0
  public void sendSmtpTestMail(
      String smtpFromMail,
      String smtpHost,
      Integer smtpPort,
      String smtpUsername,
      String smtpPassword,
      String toMail) {
    SystemConfig systemConfig = SystemConfigUtil.getSystemConfig();
    MailConfig mailConfig = TemplateConfigUtil.getMailConfig(MailConfig.SMTP_TEST);
    String subject = mailConfig.getSubject();
    String templateFilePath = mailConfig.getTemplateFilePath();
    try {
      email = new HtmlEmail();
      email.setHostName(systemConfig.getSmtpHost());
      email.setSmtpPort(systemConfig.getSmtpPort());
      email.setAuthenticator(
          new DefaultAuthenticator(systemConfig.getSmtpUsername(), systemConfig.getSmtpPassword()));
      email.setSSLOnConnect(true);

      WebAppResourceLoader resourceLoader = new WebAppResourceLoader();
      Configuration cfg = Configuration.defaultConfiguration();
      GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
      Template template = gt.getTemplate(templateFilePath);
      template.binding("systemConfig", systemConfig);
      String text = template.render();

      email.setFrom(
          MimeUtility.encodeWord(systemConfig.getShopName())
              + " <"
              + systemConfig.getSmtpFromMail()
              + ">");
      email.setSubject(subject);
      email.setMsg(text);
      email.addTo(toMail);
      email.send();

    } catch (EmailException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemple #5
0
  /**
   * 添加附件
   *
   * @param filename String
   */
  public boolean addFileAffix(String filename) {

    System.out.println("增加邮件附件:" + filename);
    try {
      BodyPart bp = new MimeBodyPart();
      FileDataSource fileds = new FileDataSource(filename);
      bp.setDataHandler(new DataHandler(fileds));
      String attachName = fileds.getName();
      //            System.out.println(attachName);
      //            System.out.println(new String(attachName.getBytes("utf-8"),"gbk"));
      //            System.out.println(new String(MimeUtility.encodeWord("")));
      attachName = new String(MimeUtility.encodeWord(attachName));
      bp.setFileName(attachName);

      mp.addBodyPart(bp);

      return true;
    } catch (Exception e) {
      System.err.println("增加邮件附件:" + filename + "发生错误!" + e);
      return false;
    }
  }
Exemple #6
0
  public boolean sendMail(
      String subject, String templateFilePath, Map<String, Object> data, String toMail) {
    boolean isSend = false;
    try {
      SystemConfig systemConfig = SystemConfigUtil.getSystemConfig();

      email = new HtmlEmail();
      email.setHostName(systemConfig.getSmtpHost());
      email.setSmtpPort(systemConfig.getSmtpPort());
      email.setAuthenticator(
          new DefaultAuthenticator(systemConfig.getSmtpUsername(), systemConfig.getSmtpPassword()));
      email.setSSLOnConnect(true);

      WebAppResourceLoader resourceLoader = new WebAppResourceLoader();
      Configuration cfg = Configuration.defaultConfiguration();
      GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
      Template template = gt.getTemplate(templateFilePath);
      template.binding(data);
      String text = template.render();

      email.setFrom(
          MimeUtility.encodeWord(systemConfig.getShopName())
              + " <"
              + systemConfig.getSmtpFromMail()
              + ">");
      email.setSubject(subject);
      email.setMsg(text);
      email.addTo(toMail);
      email.send();
      isSend = true;
    } catch (EmailException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return isSend;
  }
Exemple #7
0
  /**
   * メールを送信する
   *
   * @param fad 送信元アドレス
   * @param fan 送信元名
   * @param tad 送信先アドレス
   * @param tan 送信先名
   * @param tle タイトル
   * @param mes 本文
   * @param atd 添付ファイルパス
   * @author kazua
   */
  public String sendMailProc(
      String fad, String fan, String tad, String tan, String tle, String mes, String atd) {
    try {
      // プロパティ作成
      Properties ppt = System.getProperties();

      // メールパターンマッチ
      Pattern ptn = Pattern.compile(mailP);
      Matcher mc = ptn.matcher(fad);
      if (!mc.matches()) {
        return "送信元メールアドレスが異常です:" + fad;
      }
      mc = ptn.matcher(tad);
      if (!mc.matches()) {
        return "送信先メールアドレスが異常です:" + tad;
      }

      // パラメータチェック
      if ((tle == null || tle.equals(""))
          && (mes == null || mes.equals(""))
          && (atd == null || atd.equals(""))) {
        return "タイトル、本文、添付ファイルが全て未指定です";
      }

      // SMTPアドレス設定
      ppt.put("mail.smtp.host", "***.***.***.***");

      // メールセッション作成
      Session ssm = Session.getDefaultInstance(ppt, null);
      MimeMessage mms = new MimeMessage(ssm);

      // 送信元設定
      mms.setFrom(new InternetAddress(fad, MimeUtility.encodeWord(fan, "UTF-8", "B")));

      // 送信先設定
      InternetAddress adr = new InternetAddress(tad, MimeUtility.encodeWord(tan, "UTF-8", "B"));
      mms.setRecipient(Message.RecipientType.TO, adr);

      // メール形式設定
      mms.setHeader("Content-Type", "text/plain");

      // 題名設定
      if (tle != null && !tle.equals("")) {
        mms.setSubject(MimeUtility.encodeText(tle, "UTF-8", "B"));
      }

      // メール本体作成
      MimeMultipart mmp = new MimeMultipart();

      // 本文設定
      if (mes != null && !mes.equals("")) {
        MimeBodyPart tpt = new MimeBodyPart();
        tpt.setContent(mes, "text/plain; charset=\"UTF-8\"");
        mmp.addBodyPart(tpt);
      }

      // 添付ファイル設定
      if (atd != null && !atd.equals("")) {
        MimeBodyPart mbp = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(atd);
        DataHandler dhr = new DataHandler(fds);
        mbp.setDataHandler(dhr);
        mbp.setFileName(MimeUtility.encodeText(fds.getName(), "iso-2022-jp", "B"));
        mmp.addBodyPart(mbp);
      }

      mms.setContent(mmp);

      // メール送信
      Transport.send(mms);

      return "メール送信完了";
    } catch (Exception e) {
      return "メール送信失敗:" + e.toString();
    }
  }