Ejemplo n.º 1
0
  protected static Future<MimeMessage> send(final MailMessage m) {
    if (session == null) {
      setup("localhost");
    }
    if (m.from == null) {
      m.from = from;
    }
    return service.submit(
        new Callable<MimeMessage>() {
          @Override
          public MimeMessage call() throws Exception {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(m.from));
            message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(m.to));
            message.setSubject(m.subject);
            if (m.replyTo != null) {
              message.setReplyTo(new javax.mail.Address[] {new InternetAddress(m.replyTo)});
            }

            MimeMultipart content = new MimeMultipart();
            if (m.message != null) {

              MimeBodyPart mimeBodyPart = new MimeBodyPart();
              mimeBodyPart.setText(m.message);
              content.addBodyPart(mimeBodyPart);
            }

            if (m.htmlMessage != null) {
              if (content.getCount() > 0) {
                MimeMultipart alternative = new MimeMultipart("alternative");
                alternative.addBodyPart(content.getBodyPart(0));
                content = alternative;
              }
              MimeBodyPart mimeBodyPart = new MimeBodyPart();
              mimeBodyPart.setContent(m.htmlMessage, "text/html");
              content.addBodyPart(mimeBodyPart);
            }

            if (m.attachments.size() > 0) {
              MimeMultipart mixed = new MimeMultipart("mixed");
              MimeBodyPart body = new MimeBodyPart();
              body.setContent(content);
              mixed.addBodyPart(body);
              content = mixed;
              for (MailAttachment ma : m.attachments) {
                MimeBodyPart attachment = new MimeBodyPart();
                DataSource source = new FileDataSource(ma.file);
                attachment.setDisposition(Part.ATTACHMENT);
                attachment.setDataHandler(new DataHandler(source));
                attachment.setFileName(ma.getName());
                content.addBodyPart(attachment);
              }
            }

            message.setContent(content);
            Transport.send(message);
            logger.info("Sent email to [{}] with subject [{}].", m.to, m.subject);
            if (m.attachments.size() > 0) {
              logger.info("[{}] attachments sent.", m.attachments.size());
            }
            return message;
          }
        });
  }