示例#1
0
  /**
   * Send <strong><em>one</em></strong> mail to multiple recipients and multiple BCC recipients
   * <em>(in one mail)</em>.
   *
   * @param transport transport connection, if null transport is create inside the method
   * @param sender the "From" field
   * @param recipients the "To" field with multiple addresses.
   * @param bccRecipients the "Bcc" field with multiple addresses.
   * @param subject the Subject of the message
   * @param content the Content of the message
   * @param isHTML flag indicating wether the Content is html (<code>true</code>) or text (<code>
   *     false</code>)
   * @throws MessagingException Forwarded exception from javax.mail
   * @throws IllegalArgumentException if no recipient provided or no sender
   */
  public void sendMail(
      Transport transport,
      InternetAddress sender,
      List<InternetAddress> recipients,
      List<InternetAddress> ccRecipients,
      List<InternetAddress> bccRecipients,
      String subject,
      String content,
      String txtContent,
      boolean isHTML,
      Collection<Attachment> attachments)
      throws MessagingException {

    String recipientsStr = new LinkedList<InternetAddress>(recipients).toString();

    if (sender == null || recipients == null || recipients.size() == 0) {
      throw new IllegalArgumentException(
          "Sender null (sender: " + sender + ") or no recipient: " + recipients);
    }

    if (props != null) {
      logger.info(
          "Sending mail with subject: "
              + subject
              + " to: "
              + recipients.size()
              + " recipients: "
              + recipientsStr
              + "\n"
              + "Using smtp: "
              + props.getProperty(SMTP_HOST_PARAM, DEFAULT_SMTP_HOST)
              + " / "
              + props.getProperty(SMTP_USER_PARAM)
              + " / "
              + props.getProperty(SMTP_PASSWORD_PARAM));
    }

    Date sendDate = new Date();

    if (!DEBUG) {
      Session mailSession = Session.getDefaultInstance(props);

      MimeMessage msg = new MimeMessage(mailSession);
      msg.setSentDate(sendDate);
      msg.setFrom(sender);
      msg.setRecipients(
          Message.RecipientType.TO, recipients.toArray(new InternetAddress[recipients.size()]));
      if (ccRecipients != null && ccRecipients.size() > 0) {
        msg.setRecipients(
            Message.RecipientType.CC,
            ccRecipients.toArray(new InternetAddress[ccRecipients.size()]));
      }
      if (bccRecipients != null && bccRecipients.size() > 0) {
        msg.setRecipients(
            Message.RecipientType.BCC,
            bccRecipients.toArray(new InternetAddress[bccRecipients.size()]));
      }
      msg.setSubject(subject, ContentContext.CHARACTER_ENCODING);

      if (isHTML) {
        MimeBodyPart wrap = new MimeBodyPart();
        MimeMultipart cover = new MimeMultipart("alternative");

        MimeBodyPart bp = new MimeBodyPart();
        if (txtContent == null) {
          txtContent = StringHelper.html2txt(content);
        }
        bp.setText(txtContent, ContentContext.CHARACTER_ENCODING);
        cover.addBodyPart(bp);
        bp = new MimeBodyPart();
        bp.setText(content, ContentContext.CHARACTER_ENCODING, "html");
        cover.addBodyPart(bp);
        wrap.setContent(cover);

        MimeMultipart contentMail = new MimeMultipart("related");

        if (attachments != null) {
          for (Attachment attach : attachments) {
            String id = UUID.randomUUID().toString();
            /*
             * sb.append("<img src=\"cid:"); sb.append(id);
             * sb.append("\" alt=\"ATTACHMENT\"/>\n");
             */

            MimeBodyPart attachment = new MimeBodyPart();

            DataSource fds =
                new ByteArrayDataSource(
                    attach.getData(),
                    ResourceHelper.getFileExtensionToMineType(
                        StringHelper.getFileExtension(attach.getName())));
            attachment.setDataHandler(new DataHandler(fds));
            attachment.setHeader("Content-ID", "<" + id + ">");
            attachment.setFileName(attach.getName());

            contentMail.addBodyPart(attachment);
          }
        }

        contentMail.addBodyPart(wrap);
        msg.setContent(contentMail);
        msg.setSentDate(new Date());

      } else {
        assert attachments == null : "no attachements in text format.";
        msg.setText(content);
      }

      /*
       * if (isHTML) { msg.addHeader("Content-Type",
       * "text/html; charset=\"" + ContentContext.CHARACTER_ENCODING +
       * "\""); }
       */

      msg.saveChanges();

      if (transport == null || !transport.isConnected()) {
        transport = getMailTransport(staticConfig);
        try {
          transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
          transport.close();
        }
      } else {
        transport.sendMessage(msg, msg.getAllRecipients());
      }

    } else {
      FileOutputStream out = null;
      try {
        PrintStream w = System.out;
        if (tempDir != null && new File(tempDir).exists()) {
          File mailFile =
              new File(
                  tempDir,
                  "mail-debug/mail-"
                      + StringHelper.renderFileTime(sendDate)
                      + "-"
                      + StringHelper.stringToFileName(subject)
                      + ".txt");
          mailFile.getParentFile().mkdirs();
          out = new FileOutputStream(mailFile, true);
          w = new PrintStream(mailFile, ContentContext.CHARACTER_ENCODING);
        } else {
          w.println("");
        }

        w.println("FROM:");
        w.println(sender.toString());
        w.print("TO: #");
        w.println(Integer.toString(recipients.size()));
        for (InternetAddress recipient : recipients) {
          w.println(recipient.toString());
        }
        if (ccRecipients != null) {
          w.print("CC: #");
          w.println(Integer.toString(ccRecipients.size()));
          for (InternetAddress ccRecipient : ccRecipients) {
            w.println(ccRecipient.toString());
          }
        }
        if (bccRecipients != null) {
          w.print("BCC: #");
          w.println(Integer.toString(bccRecipients.size()));
          for (InternetAddress bccRecipient : bccRecipients) {
            w.println(bccRecipient.toString());
          }
        }
        w.println("SUBJECT:");
        w.println(subject);
        w.print("IS HTML: ");
        w.println(isHTML);
        w.println("CONTENT:");
        w.print("--BEGIN--");
        w.print(content);
        w.println("--END--");
        w.println("");
        w.flush();
      } catch (IOException e) {
        throw new RuntimeException("Exception when writing debug mail file.", e);
      } finally {
        ResourceHelper.safeClose(out);
      }
    }
    logger.info("Mail sent to: " + recipientsStr);
  }