private MimeBodyPart getContent(
      final EmailType type,
      final AbstractBuild<?, ?> build,
      BuildListener listener,
      String charset,
      EmailTrigger trigger)
      throws MessagingException {
    final String text = new ContentBuilder().transformText(type.getBody(), this, build, listener);

    String messageContentType = contentType;
    // contentType is null if the project was not reconfigured after upgrading.
    if (messageContentType == null || "default".equals(messageContentType)) {
      messageContentType = DESCRIPTOR.getDefaultContentType();
      // The defaultContentType is null if the main Jenkins configuration
      // was not reconfigured after upgrading.
      if (messageContentType == null) {
        messageContentType = "text/plain";
      }
    }
    messageContentType += "; charset=" + charset;

    try {
      if (saveOutput) {
        Random random = new Random();
        String extension = ".html";
        if (messageContentType.startsWith("text/plain")) {
          extension = ".txt";
        }

        FilePath savedOutput =
            new FilePath(
                build.getWorkspace(),
                String.format(
                    "%s-%s%d%s",
                    trigger.getDescriptor().getDisplayName(),
                    build.getId(),
                    random.nextInt(),
                    extension));
        savedOutput.write(text, charset);
      }
    } catch (IOException e) {
      listener.getLogger().println("Error trying to save email output to file. " + e.getMessage());
    } catch (InterruptedException e) {
      listener.getLogger().println("Error trying to save email output to file. " + e.getMessage());
    }

    // set the email message text
    // (plain text or HTML depending on the content type)
    MimeBodyPart msgPart = new MimeBodyPart();
    debug(listener.getLogger(), "messageContentType = %s", messageContentType);
    if (messageContentType.startsWith("text/html")) {
      String inlinedCssHtml = new CssInliner().process(text);
      msgPart.setContent(inlinedCssHtml, messageContentType);
    } else {
      msgPart.setContent(text, messageContentType);
    }
    return msgPart;
  }
 private void setSubject(
     final EmailType type,
     final AbstractBuild<?, ?> build,
     MimeMessage msg,
     BuildListener listener,
     String charset)
     throws MessagingException {
   String subject = new ContentBuilder().transformText(type.getSubject(), this, build, listener);
   msg.setSubject(subject, charset);
 }
  private MimeMessage createMail(
      EmailType type, AbstractBuild<?, ?> build, BuildListener listener, EmailTrigger trigger)
      throws MessagingException, IOException, InterruptedException {
    boolean overrideGlobalSettings = ExtendedEmailPublisher.DESCRIPTOR.getOverrideGlobalSettings();

    MimeMessage msg;

    // If not overriding global settings, use the Mailer class to create a session and set the from
    // address
    // Else we'll do it ourselves
    if (!overrideGlobalSettings) {
      debug(
          listener.getLogger(),
          "NOT overriding default server settings, using Mailer to create session");
      msg = new MimeMessage(Mailer.descriptor().createSession());
      msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress()));
    } else {
      debug(listener.getLogger(), "Overriding default server settings, creating our own session");
      msg = new MimeMessage(ExtendedEmailPublisher.DESCRIPTOR.createSession());
      msg.setFrom(new InternetAddress(ExtendedEmailPublisher.DESCRIPTOR.getAdminAddress()));
    }

    String charset = Mailer.descriptor().getCharset();
    if (overrideGlobalSettings) {
      String overrideCharset = ExtendedEmailPublisher.DESCRIPTOR.getCharset();
      if (StringUtils.isNotBlank(overrideCharset)) {
        debug(listener.getLogger(), "Overriding charset %s", overrideCharset);
        charset = overrideCharset;
      }
    }

    // Set the contents of the email
    msg.addHeader("X-Jenkins-Job", build.getProject().getDisplayName());
    if (build.getResult() != null) {
      msg.addHeader("X-Jenkins-Result", build.getResult().toString());
    }
    msg.setSentDate(new Date());
    setSubject(type, build, msg, listener, charset);

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(getContent(type, build, listener, charset, trigger));

    AttachmentUtils attachments = new AttachmentUtils(attachmentsPattern);
    attachments.attach(multipart, this, build, listener);

    // add attachments from the email type if they are setup
    if (StringUtils.isNotBlank(type.getAttachmentsPattern())) {
      AttachmentUtils typeAttachments = new AttachmentUtils(type.getAttachmentsPattern());
      typeAttachments.attach(multipart, this, build, listener);
    }

    if (attachBuildLog || type.getAttachBuildLog()) {
      debug(listener.getLogger(), "Request made to attach build log");
      AttachmentUtils.attachBuildLog(
          multipart, build, listener, compressBuildLog || type.getCompressBuildLog());
    }

    msg.setContent(multipart);

    EnvVars env = null;
    try {
      env = build.getEnvironment(listener);
    } catch (Exception e) {
      listener.getLogger().println("Error retrieving environment vars: " + e.getMessage());
      // create an empty set of env vars
      env = new EnvVars();
    }

    // Get the recipients from the global list of addresses
    Set<InternetAddress> recipientAddresses = new LinkedHashSet<InternetAddress>();
    Set<InternetAddress> ccAddresses = new LinkedHashSet<InternetAddress>();
    if (type.getSendToRecipientList()) {
      debug(listener.getLogger(), "Adding recipients from recipient list");
      addAddressesFromRecipientList(
          recipientAddresses,
          ccAddresses,
          getRecipientList(type, build, recipientList, listener, charset),
          env,
          listener);
    }
    // Get the list of developers who made changes between this build and the last
    // if this mail type is configured that way
    if (type.getSendToDevelopers()) {
      debug(listener.getLogger(), "Adding developers");
      Set<User> users;
      if (type.getIncludeCulprits()) {
        users = build.getCulprits();
      } else {
        users = new HashSet<User>();
        for (Entry change : build.getChangeSet()) {
          users.add(change.getAuthor());
        }
      }

      for (User user : users) {
        if (!isExcludedCommitter(user.getFullName())) {
          String userAddress = EmailRecipientUtils.getUserConfiguredEmail(user);
          if (userAddress != null) {
            addAddressesFromRecipientList(
                recipientAddresses, ccAddresses, userAddress, env, listener);
          } else {
            listener
                .getLogger()
                .println(
                    "Failed to send e-mail to "
                        + user.getFullName()
                        + " because no e-mail address is known, and no default e-mail domain is configured");
          }
        }
      }
    }

    if (type.isSendToRequester()) {
      debug(listener.getLogger(), "Sending to requester");
      // looking for Upstream build.
      AbstractBuild<?, ?> cur = build;
      Cause.UpstreamCause upc = build.getCause(Cause.UpstreamCause.class);
      while (upc != null) {
        // UpstreamCause.getUpStreamProject() returns the full name, so use getItemByFullName
        AbstractProject<?, ?> p =
            (AbstractProject<?, ?>)
                Hudson.getInstance().getItemByFullName(upc.getUpstreamProject());
        cur = p.getBuildByNumber(upc.getUpstreamBuild());
        upc = cur.getCause(Cause.UpstreamCause.class);
      }
      addUserTriggeringTheBuild(cur, recipientAddresses, ccAddresses, env, listener);
    }

    // Get the list of recipients that are uniquely specified for this type of email
    if (StringUtils.isNotBlank(type.getRecipientList())) {
      addAddressesFromRecipientList(
          recipientAddresses,
          ccAddresses,
          getRecipientList(type, build, type.getRecipientList(), listener, charset),
          env,
          listener);
    }

    String emergencyReroute = ExtendedEmailPublisher.DESCRIPTOR.getEmergencyReroute();
    boolean isEmergencyReroute = StringUtils.isNotBlank(emergencyReroute);

    if (isEmergencyReroute) {
      debug(listener.getLogger(), "Emergency reroute turned on");
      recipientAddresses.clear();
      addAddressesFromRecipientList(
          recipientAddresses, ccAddresses, emergencyReroute, env, listener);
      listener.getLogger().println("Emergency reroute is set to: " + emergencyReroute);
    }

    msg.setRecipients(
        Message.RecipientType.TO,
        recipientAddresses.toArray(new InternetAddress[recipientAddresses.size()]));
    if (ccAddresses.size() > 0) {
      msg.setRecipients(
          Message.RecipientType.CC, ccAddresses.toArray(new InternetAddress[ccAddresses.size()]));
    }

    Set<InternetAddress> replyToAddresses = new LinkedHashSet<InternetAddress>();
    if (StringUtils.isNotBlank(replyTo)) {
      addAddressesFromRecipientList(
          replyToAddresses,
          null,
          getRecipientList(type, build, replyTo, listener, charset),
          env,
          listener);
    }

    if (StringUtils.isNotBlank(type.getReplyTo())) {
      addAddressesFromRecipientList(
          replyToAddresses,
          null,
          getRecipientList(type, build, type.getReplyTo(), listener, charset),
          env,
          listener);
    }

    if (replyToAddresses.size() > 0) {
      msg.setReplyTo(replyToAddresses.toArray(new InternetAddress[replyToAddresses.size()]));
    }

    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
      // Send mails as replies until next successful build
      MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
      if (b != null && pb.getResult() != Result.SUCCESS) {
        debug(listener.getLogger(), "Setting In-Reply-To since last build was not successful");
        msg.setHeader("In-Reply-To", b.messageId);
        msg.setHeader("References", b.messageId);
      }
    }

    if (CONTENT_TRANSFER_ENCODING != null) {
      msg.setHeader("Content-Transfer-Encoding", CONTENT_TRANSFER_ENCODING);
    }

    String listId = ExtendedEmailPublisher.DESCRIPTOR.getListId();
    if (listId != null) {
      msg.setHeader("List-ID", listId);
    }

    if (ExtendedEmailPublisher.DESCRIPTOR.getPrecedenceBulk()) {
      msg.setHeader("Precedence", "bulk");
    }

    return msg;
  }