Пример #1
0
  @Override
  protected void sendInternal(
      Map.Entry<String, String> from,
      Map.Entry<String, String> replyTo,
      Map<String, String> to,
      Map<String, String> cc,
      Map<String, String> bcc,
      String subject,
      Object body,
      List<Attachment> attachments) {
    try {
      Session emailSession = getSession();

      Message message = new MimeMessage(emailSession);
      message.setFrom(emailAddress(from));
      if (replyTo != null) {
        message.setReplyTo(new Address[] {emailAddress(replyTo)});
      }

      message.setSubject(subject);

      BasicViewRenderer viewRenderer = render(body);
      String content = viewRenderer.getOutputAsString();
      String contentType = ContentType.cleanContentType(viewRenderer.getContentType());
      contentType = StringUtils.isBlank(contentType) ? ContentType.TextHtml.value() : contentType;

      if (Expressive.isEmpty(attachments)) {
        message.setContent(content, contentType);
      } else {
        Multipart multipart =
            new MimeMultipart(
                "mixed"); // subtype must be "mixed" or inline & regular attachments won't play well
        // together
        addBody(multipart, content, contentType);
        addAttachments(multipart, attachments);
        message.setContent(multipart);
      }

      addRecipients(to, message, RecipientType.TO);
      addRecipients(cc, message, RecipientType.CC);
      addRecipients(bcc, message, RecipientType.BCC);

      sendMessage(message);
    } catch (MessagingException e) {
      throw new MailException(e, "Failed to send an email: %s", e.getMessage());
    }
  }
Пример #2
0
  private void addAttachments(Multipart multipart, List<Attachment> attachments)
      throws MessagingException {
    for (Attachment attachment : attachments) {
      BasicViewRenderer response = render(attachment.view());
      byte[] base64Encoded = Base64.encodeToByte(response.getOutputAsBytes());

      InternetHeaders headers = new InternetHeaders();
      headers.addHeader(Header.ContentType, response.getContentType());
      headers.addHeader(Header.ContentTransferEncoding, "base64");

      MimeBodyPart part = new MimeBodyPart(headers, base64Encoded);
      part.setFileName(attachment.name());
      part.setDisposition(attachment.disposition().value());

      if (attachment.isInline()) {
        part.setContentID(attachment.contentId());
      }

      multipart.addBodyPart(part);
    }
  }