private void sendReplyFromPostmaster(Mail mail, String stringContent) {
    try {
      MailAddress notifier = getMailetContext().getPostmaster();

      MailAddress senderMailAddress = mail.getSender();

      MimeMessage message = mail.getMessage();
      // Create the reply message
      MimeMessage reply = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));

      // Create the list of recipients in the Address[] format
      InternetAddress[] rcptAddr = new InternetAddress[1];
      rcptAddr[0] = senderMailAddress.toInternetAddress();
      reply.setRecipients(Message.RecipientType.TO, rcptAddr);

      // Set the sender...
      reply.setFrom(notifier.toInternetAddress());

      // Create the message body
      MimeMultipart multipart = new MimeMultipart();
      // Add message as the first mime body part
      MimeBodyPart part = new MimeBodyPart();
      part.setContent(stringContent, "text/plain");
      part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
      multipart.addBodyPart(part);

      reply.setContent(multipart);
      reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());

      // Create the list of recipients in our MailAddress format
      Set<MailAddress> recipients = new HashSet<MailAddress>();
      recipients.add(senderMailAddress);

      // Set additional headers
      if (reply.getHeader(RFC2822Headers.DATE) == null) {
        reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new java.util.Date()));
      }
      String subject = message.getSubject();
      if (subject == null) {
        subject = "";
      }
      if (subject.indexOf("Re:") == 0) {
        reply.setSubject(subject);
      } else {
        reply.setSubject("Re:" + subject);
      }
      reply.setHeader(RFC2822Headers.IN_REPLY_TO, message.getMessageID());

      // Send it off...
      getMailetContext().sendMail(notifier, recipients, reply);
    } catch (Exception e) {
      log("Exception found sending reply", e);
    }
  }
 private MimeMessage getMockedMimeMessage() throws MessagingException {
   MimeMessage mockedMimeMessage = MailUtil.createMimeMessage();
   mockedMimeMessage.setHeader(HEADER1, "true");
   mockedMimeMessage.setHeader(HEADER2, "true");
   mockedMimeMessage.saveChanges();
   return mockedMimeMessage;
 }
예제 #3
0
 protected void injectMailHeader(MimeMessage mm) {
   for (Object name : mailHeaders.keySet()) {
     try {
       mm.setHeader((String) name, mailHeaders.getProperty((String) name));
     } catch (MessagingException e) {
       e.printStackTrace();
     }
   }
 }
예제 #4
0
  public void sendEmail() throws MessagingException {
    if (msg.getFrom() == null)
      msg.setFrom(new InternetAddress("*****@*****.**"));
    msg.setHeader("X-mailer", "msgsend");
    msg.setRecipients(Message.RecipientType.TO, (Address[]) toList.toArray(new Address[0]));
    msg.setRecipients(Message.RecipientType.CC, (Address[]) ccList.toArray(new Address[0]));
    msg.setRecipients(Message.RecipientType.BCC, (Address[]) bccList.toArray(new Address[0]));
    msg.setSentDate(new Date());

    if (!toList.isEmpty()) Transport.send(msg);
  }
예제 #5
0
 /**
  * Takes the message and adds a header to it.
  *
  * @param mail the mail being processed
  * @throws MessagingException if an error arises during message processing
  */
 public void service(Mail mail) {
   try {
     MimeMessage message = mail.getMessage();
     Classifier classifier = new Classifier(message);
     String classification = classifier.getClassification();
     // if ( !classification.equals("Normal") ) {
     message.setHeader(headerName, classification);
     message.saveChanges();
     // }
   } catch (javax.mail.MessagingException me) {
     log("Error classifying message: " + me.getMessage());
   }
 }
예제 #6
0
  public void sendMail(
      String to,
      String from,
      String fromName,
      String fromCharcode,
      String subject,
      String subjectCharcode,
      String message,
      String messageCharcode,
      String contentType,
      String contentTransferEncoding)
      throws SmtpAccessException {
    try {
      Properties prop = System.getProperties();
      prop.setProperty("mail.smtp.host", smtpServer);
      MimeMessage mime = new MimeMessage(Session.getDefaultInstance(prop));

      mime.setFrom(new InternetAddress(from, fromName, fromCharcode));
      mime.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
      mime.setSubject(subject, subjectCharcode);
      mime.setText(message.toString(), messageCharcode);
      if (contentType != null) {
        mime.setHeader("Content-Type", contentType);
      } else {
        mime.setHeader("Content-Type", "text/plain");
      }
      if (contentTransferEncoding != null) {
        mime.setHeader("Content-Transfer-Encoding", contentTransferEncoding);
      } else {
        mime.setHeader("Content-Transfer-Encoding", "7bit");
      }
      mime.setSentDate(new java.util.Date());
      Transport.send(mime);
    } catch (Exception e) {
      throw new SmtpAccessException(e);
    }
  }
예제 #7
0
 /**
  * It creates a new MimeMessage with standard Aspirin ID header.
  *
  * @return new MimeMessage object
  */
 public MimeMessage createNewMimeMessage() {
   if (defaultSession == null) {
     defaultSession = Session.getDefaultInstance(System.getProperties());
   }
   MimeMessage mMesg = new MimeMessage(defaultSession);
   synchronized (idCounterLock) {
     long nowTime = System.currentTimeMillis() / 1000;
     String newId = nowTime + "." + Integer.toHexString(idCounter++);
     try {
       mMesg.setHeader(Aspirin.HEADER_MAIL_ID, newId);
     } catch (MessagingException msge) {
       log.warn("Aspirin Mail ID could not be generated.", msge);
       msge.printStackTrace();
     }
   }
   return mMesg;
 }
예제 #8
0
 /**
  * Factory method to add a message by specifying its fields.
  *
  * <p>To use more advanced message features, use the <code>addMessage(Message message)</code>
  * method.
  *
  * <p>If parts of the message are invalid (ie, the toEmail is null) the message won't be sent.
  *
  * @param toName the name of the recipient of this email.
  * @param toEmail the email address of the recipient of this email.
  * @param fromName the name of the sender of this email.
  * @param fromEmail the email address of the sender of this email.
  * @param subject the subject of the email.
  * @param body the body of the email.
  * @param format text/html or text/plain
  */
 public void addMessage(
     String toName,
     String toEmail,
     String fromName,
     String fromEmail,
     String subject,
     String body,
     String format) {
   // Check for errors in the given fields:
   if (toEmail == null || fromEmail == null || subject == null || body == null) {
     System.err.println("Error sending email in EmailTask.java: " + "Invalid fields.");
   } else {
     try {
       MimeMessage message = createMessage();
       Address to = null;
       Address from = null;
       if (toEmail != null) {
         if (toName != null) {
           to = new InternetAddress(toEmail, toName);
         } else {
           to = new InternetAddress(toEmail);
         }
       }
       if (fromEmail != null) {
         if (fromName != null) {
           from = new InternetAddress(fromEmail, fromName);
         } else {
           from = new InternetAddress(fromEmail);
         }
       }
       message.setRecipient(Message.RecipientType.TO, to);
       message.setFrom(from);
       message.setSubject(subject);
       message.setText(body, "UTF-8");
       // more details: http://www.vipan.com/htdocs/javamail.html
       message.setHeader("Content-Type", format + "; charset=utf-8");
       /**
        * msg.setDataHandler(new DataHandler( new ByteArrayDataSource(mail.getContent(),
        * "text/html"))); msg.setHeader("X-Mailer", "JavaMailer");
        */
       addMessage(message);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
예제 #9
0
  private static MimeMessage createMessage(
      String from, String[] to, String subject, MimeMultipart content) throws MessagingException {
    Session session = Session.getInstance(System.getProperties());
    session.setDebug(true);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));

    for (String aTo : to) {
      message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(aTo, false));
    }

    message.setSubject(subject);
    message.setContent(content);
    message.setHeader("X-Mailer", "iComp");
    message.setSentDate(new Date());
    return message;
  }
 /**
  * Validate signed mail.
  *
  * @param mime
  * @param mailMsg
  * @return
  * @throws MessagingException
  * @throws IOException
  * @throws CMSException
  * @throws CertificateException
  * @throws OperatorCreationException
  */
 private boolean validateSignedMail(MimeMessage mime, MailMessage mailMsg)
     throws MessagingException, CMSException, IOException, OperatorCreationException,
         CertificateException {
   boolean verify = false;
   /*
    * Add a header to make a new message in order to fix the issue of Outlook
    *
    * @see http://www.bouncycastle.org/wiki/display/JA1/CMS+and+SMIME+APIs
    *
    * @see http://stackoverflow.com/questions/8590426/s-mime-verification-with- x509-certificate
    */
   MimeMessage newmsg = new MimeMessage(mime);
   newmsg.setHeader("Nothing", "Add a header for verifying signature only.");
   newmsg.saveChanges();
   SMIMESigned signed = new SMIMESigned((MimeMultipart) newmsg.getContent());
   verify = this.isValid(signed, mailMsg);
   return verify;
 }
예제 #11
0
  public static void main(String[] a) {

    final String username = "******";

    final String password = "******";

    Properties props = new Properties();

    props.put("mail.smtp.auth", "true");

    props.put("mail.smtp.host", "mail.vms.com.vn");

    String to = "*****@*****.**";
    String subject = "abc";
    String body = createBody("aaaaaaa");
    /*Doan nay ben em dang dung IP*/

    Session session =
        Session.getInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
              }
            });

    try {

      MimeMessage mimeMessage = new MimeMessage(session);
      mimeMessage.setHeader("Content-Type", "text/html; charset=UTF-8");
      mimeMessage.setFrom(new InternetAddress(username));
      mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
      mimeMessage.setSubject(subject, "utf-8");
      mimeMessage.setContent(body, "text/html; charset=UTF-8");

      Transport.send(mimeMessage);

      System.out.println("Done");

    } catch (MessagingException e) {

      throw new RuntimeException(e);
    }
  }
예제 #12
0
  /**
   * 此段代码用来发送普通电子邮件
   *
   * @throws MessagingException
   * @throws UnsupportedEncodingException
   * @throws UnsupportedEncodingException
   */
  public void send() throws MessagingException, UnsupportedEncodingException {
    Properties props = new Properties();
    Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(props, auth);
    // 设置session,和邮件服务器进行通讯。
    MimeMessage message = new MimeMessage(session);
    // message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
    message.setSubject(mail_subject); // 设置邮件主题
    message.setText(mail_body); // 设置邮件正文
    message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题

    message.setSentDate(new Date()); // 设置邮件发送日期
    Address address = new InternetAddress(mail_from, personalName);
    message.setFrom(address); // 设置邮件发送者的地址
    Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Transport.send(message); // 发送邮件
  }
예제 #13
0
  public MimeMessage createMimeMessage(Session mailSession) {
    try {
      MimeMessage msg = new MimeMessage(mailSession);
      msg.setSubject(this.getSubject(), "UTF-8");
      Address[] jRecipients;

      if (recipients != null) {
        jRecipients = new Address[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
          jRecipients[i] =
              new InternetAddress(recipients[i].getPostingEmail(), recipients[i].getFullName());
        }
        msg.setRecipients(RecipientType.TO, jRecipients);
      }

      msg.setText(getBody(), "UTF-8");
      msg.setHeader("Content-Type", "text/html;charset=UTF-8");

      return msg;
    } catch (MessagingException | UnsupportedEncodingException me) {
      throw new EnvironmentResourceException("Error when sending the mail confirmation.", me);
    }
  }
예제 #14
0
  protected MimeMessage buildMessage(
      Collection<String> tos,
      Collection<String> ccs,
      Collection<String> bccs,
      Map<String, String> headers,
      String subject,
      String body)
      throws MailerException {

    Session session = Session.getDefaultInstance(getConfiguration());
    MimeMessage message = new MimeMessage(session);

    try {
      if (isDebug()) {
        for (InternetAddress address : convertStringsToAddressess(getList(getDebugAddress()))) {
          message.addRecipient(javax.mail.Message.RecipientType.TO, address);
        }
      } else {
        for (String address : tos) {
          message.addRecipient(
              javax.mail.Message.RecipientType.TO, convertStringToAddress(address));
        }
        if (ccs != null) {
          for (String address : ccs) {
            message.addRecipient(
                javax.mail.Message.RecipientType.CC, convertStringToAddress(address));
          }
        }
        if (bccs != null) {
          for (String address : bccs) {
            message.addRecipient(
                javax.mail.Message.RecipientType.BCC, convertStringToAddress(address));
          }
        }
      }
      message.setSubject(subject);

      Multipart mp = new MimeMultipart();

      BodyPart messageBodyText = new MimeBodyPart();
      messageBodyText.setContent(body, getBodyPartType());

      mp.addBodyPart(messageBodyText);

      if (null != getAttachmentsFiles()) {

        for (String filename : getAttachmentsFiles()) {
          File file = new File(filename);
          DataSource source = new FileDataSource(file);

          BodyPart messageAttachment = new MimeBodyPart();
          messageAttachment.setDataHandler(new DataHandler(source));

          messageAttachment.setFileName(file.getName());
          messageAttachment.setDisposition(Part.ATTACHMENT);

          String contentType = getAttachmentContentType(source.getContentType(), filename);
          messageAttachment.addHeader("Content-Type", contentType);

          mp.addBodyPart(messageAttachment);
        }
      }

      message.setContent(mp);

      if (headers != null) {
        for (String key : headers.keySet()) {
          message.addHeader(key, headers.get(key));
          message.setHeader(key, headers.get(key));
        }
      }

      message.saveChanges();
    } catch (MailerException e) {
      throw new MailerException(e);
    } catch (MessagingException e) {
      throw new MailerException(e);
    }

    return message;
  }
예제 #15
0
  /**
   * HTML 형식으로 된 메일을 보낸다.
   *
   * @param mailTo 받는사람 주소
   * @param mailFrom 보내는 사람 주소
   * @param subject 메일 제목
   * @param content HTML 메일 컨텐츠
   * @throws MessagingException
   * @throws UnsupportedEncodingException
   */
  public void sendHtmlMail(String mailTo, String mailFrom, String subject, String content)
      throws MessagingException, UnsupportedEncodingException {

    // properties object 얻기
    Properties props = System.getProperties();

    // SMTP host property 정의
    // props.put(smtpProps, smtpHost);
    props.put(SMTP_PROPS, SMTP_HOST);
    log.debug("[" + className + "]-SMTP_HOST =" + SMTP_HOST);

    // javax mail 을 디버깅 모드로 설정
    props.put(SMTP_DEBUG, SMTP_TRUE);
    log.debug("[" + className + "]-SMTP_TRUE =" + SMTP_TRUE);

    if (MarConstants.getServerName() == MarConstants.SERVER_LOCAL) {
      // gmail smtp 서비스 포트 설정
      props.put(SMTP_PORT, SMTP_PORTV2);
      props.put("type", "javax.mail.Session"); // 해도 그만 안해도 그만
      props.put("auth", "Application"); // 해도 그만 안해도 그만
      log.debug("[" + className + "]-SMTP_PORTV2 =" + SMTP_PORTV2);

      // 로그인할때 Transport Layer Security (TLS) 를 사용할것인지 설정 gmail 에선 tls가 필수가 아니므로 해도그만 안해도 그만이다.
      props.put(SMTP_TLS, SMTP_TRUE);
      props.put(SMTP_TRANS, SMTP_PROTOCOL); // 프로토콜 설정
      log.debug("[" + className + "]-filename =" + SMTP_TRUE);
      log.debug("[" + className + "]-filename =" + SMTP_PROTOCOL);

      // gmail 인증용  Secure Sockets Layer (SSL) 설정
      // gmail 에서 인증? 사용해주므로 요건 안해주면 안됨
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

    } else {
      props.put(SMTP_PORT, SMTP_PORTV);
      log.debug("[" + className + "]-filename =" + SMTP_PORTV);
    }

    // session 얻기
    Session session = null;

    if (MarConstants.getServerName() == MarConstants.SERVER_LOCAL) {
      // smtp 인증 을 설정
      props.put("mail.smtp.auth", "true");

      Authenticator auth =
          new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
              // return new PasswordAuthentication("*****@*****.**", "vlffldzm2102");
              return new PasswordAuthentication("*****@*****.**", "");
            }
          };
      // session 얻기
      session = Session.getDefaultInstance(props, auth);
      // log.debug("["+className+"]-session ="+session);
    } else {
      session = Session.getDefaultInstance(props, null);
      // log.debug("["+className+"]-session ="+session);
    }

    if (log.isDebugEnabled()) {
      session.setDebug(true);
    }

    log.debug("[" + className + "]-mailFrom =" + mailFrom);
    log.debug("[" + className + "]-mailTo =" + mailTo);

    // 새로운 message object 생성
    MimeMessage message = new MimeMessage(session);
    // MimeUtility.encodeText(subject, "KSC5601", "B");
    message.setHeader("Content-Type", "text/html; charset=" + MAIL_ENCODING);
    message.setHeader("Content-Transfer-Encoding", MAIL_ENCODING64);
    message.setSubject(subject);
    // 일반적인 message object 채우기
    // message.setContent(content, "text/html; charset=" + MAIL_ENCODING);
    // message.setContent(content, "text/html; charset=UTF-8");
    message.setContent(content, "text/html;charset=UTF-8");
    message.setFrom(new InternetAddress(mailFrom));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
    // message 보내기

    Transport.send(message);
    log.debug("[" + className + "]-Send Mail Success");
  }
예제 #16
0
  /**
   * Sent the message to a plain SMTP server like Waldo
   *
   * @param mmd the MailMessageData to send
   * @return success or failure
   */
  private boolean smtpSend(Mail mail) {
    boolean retVal = true;
    Session session = null;

    try {
      // Create a properties object
      Properties smtpProps = new Properties();

      // Add mail configuration to the properties
      smtpProps.put("mail.transport.protocol", "smtp");

      smtpProps.put("mail.smtp.host", mailConfig.getUrlSmtp());
      smtpProps.put("mail.smtp.port", mailConfig.getPortSmtp());

      if (mailConfig.isSMTPAuth()) {
        Authenticator auth = new SMTPAuthenticator();
        session = Session.getInstance(smtpProps, auth);
      } else session = Session.getDefaultInstance(smtpProps, null);

      // Display the conversation between the client and server
      if (DEBUG) session.setDebug(true);

      // Create a new message
      MimeMessage msg = new MimeMessage(session);

      // Set the single from field
      msg.setFrom(new InternetAddress(mailConfig.getUserEmail()));

      // Set the To, CC, and BCC from their ArrayLists
      for (String emailAddress : mail.getToRecipients())
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress, false));

      if (mail.getCcRecipients() != null)
        for (String emailAddress : mail.getCcRecipients())
          if (!emailAddress.equals(""))
            msg.addRecipient(Message.RecipientType.CC, new InternetAddress(emailAddress, false));

      if (mail.getBccRecipients() != null)
        for (String emailAddress : mail.getBccRecipients())
          if (!emailAddress.equals(""))
            msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(emailAddress, false));

      // Set the subject
      msg.setSubject(mail.getSubject());

      // Set the message body
      msg.setText(mail.getContent());

      // Set some other header information
      msg.setHeader("X-Mailer", "Comp Sci Tech Mailer");
      msg.setSentDate(new Date());

      if (mailConfig.isSMTPAuth()) {
        Transport transport = session.getTransport();

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
        transport.close();
      } else Transport.send(msg);

    } catch (NoSuchProviderException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is no server at the SMTP address.",
          "SMTP-NoSuchProviderException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is no server at the SMTP address.", e);
      retVal = false;
    } catch (AddressException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is an error in a recipient's address.",
          "SMTP-AddressException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is an error in a recipient's address.", e);
      retVal = false;
    } catch (MessagingException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is a problem with the message.",
          "SMTP-MessagingException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is a problem with the message.", e);
      retVal = false;
    } catch (Exception e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There has been an unknown error.",
          "SMTP-UnknownException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There has been an unknown error.", e);
      retVal = false;
    }
    return retVal;
  }
예제 #17
0
  /**
   * Sent the message to a Gmail account
   *
   * @param mmd the MailMessageData to send
   * @return success or failure
   */
  public boolean gmailSend(Mail mail) {
    boolean retVal = true;
    Transport transport = null;

    try {
      // Create a properties object
      Properties smtpProps = new Properties();

      // Add mail configuration to the properties
      smtpProps.put("mail.transport.protocol", "smtps");
      smtpProps.put("mail.smtps.host", mailConfig.getUrlSmtp());
      smtpProps.put("mail.smtps.auth", "true");
      smtpProps.put("mail.smtps.quitwait", "false");

      // Create a mail session
      Session mailSession = Session.getDefaultInstance(smtpProps);

      // Display the conversation between the client and server
      if (DEBUG) mailSession.setDebug(true);

      // Instantiate the transport object
      transport = mailSession.getTransport();

      // Create a new message
      MimeMessage msg = new MimeMessage(mailSession);

      // Set the To, CC, and BCC from their ArrayLists
      for (String emailAddress : mail.getToRecipients())
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress, false));

      if (mail.getCcRecipients() != null)
        for (String emailAddress : mail.getCcRecipients())
          msg.addRecipient(Message.RecipientType.CC, new InternetAddress(emailAddress, false));

      if (mail.getBccRecipients() != null)
        for (String emailAddress : mail.getBccRecipients())
          msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(emailAddress, false));

      // Set the subject line
      msg.setSubject(mail.getSubject());
      // Set the message body
      msg.setText(mail.getContent());

      // Set some other header information
      msg.setHeader("X-Mailer", "Comp Sci Tech Mailer");
      msg.setSentDate(new Date());

      // Connect and authenticate to the server
      transport.connect(
          mailConfig.getUrlSmtp(),
          mailConfig.getPortSmtp(),
          mailConfig.getUserNamePop3(),
          mailConfig.getUserPassPop3());

      // Send the message
      transport.sendMessage(msg, msg.getAllRecipients());

      // Close the connection
      transport.close();

    } catch (NoSuchProviderException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is no server at the SMTP address.",
          "Gmail-NoSuchProviderException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is no server at the SMTP address.", e);
      retVal = false;
    } catch (AddressException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is an error in a recipient's address.",
          "Gmail-AddressException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is an error in a recipient's address.", e);
      retVal = false;
    } catch (MessagingException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is a problem with the message.",
          "Gmail-MessagingException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is a problem with the message.", e);
      retVal = false;
    } catch (Exception e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There has been an unknown error.",
          "Gmail-UnknownException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There has been an unknown error.", e);
      retVal = false;
    }
    return retVal;
  }
  private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception {
    URL url = new URL(uri);
    String recipient = url.getPath();

    String server = null;
    String port = null;
    String sender = null;
    String subject = null;
    String username = null;
    String password = null;

    StringTokenizer headers = new StringTokenizer(url.getQuery(), "&");

    while (headers.hasMoreTokens()) {
      String token = headers.nextToken();

      if (token.startsWith("server=")) {
        server = URLDecoder.decode(token.substring("server=".length()), "UTF-8");

        continue;
      }

      if (token.startsWith("port=")) {
        port = URLDecoder.decode(token.substring("port=".length()), "UTF-8");

        continue;
      }

      if (token.startsWith("sender=")) {
        sender = URLDecoder.decode(token.substring("sender=".length()), "UTF-8");

        continue;
      }

      if (token.startsWith("subject=")) {
        subject = URLDecoder.decode(token.substring("subject=".length()), "UTF-8");

        continue;
      }

      if (token.startsWith("username="******"username="******"UTF-8");

        continue;
      }

      if (token.startsWith("password="******"password="******"UTF-8");

        continue;
      }
    }

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("smtp server '" + server + "'");

      if (username != null) {
        LOGGER.debug("smtp-auth username '" + username + "'");
      }

      LOGGER.debug("mail sender '" + sender + "'");
      LOGGER.debug("subject line '" + subject + "'");
    }

    Properties properties = System.getProperties();
    properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled()));
    properties.put("mail.smtp.from", sender);
    properties.put("mail.smtp.host", server);

    if (port != null) {
      properties.put("mail.smtp.port", port);
    }

    if (username != null) {
      properties.put("mail.smtp.auth", String.valueOf(true));
      properties.put("mail.smtp.user", username);
    }

    Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password));

    MimeMessage message = null;
    if (mediatype.startsWith("multipart/")) {
      message = new MimeMessage(session, new ByteArrayInputStream(data));
    } else {
      message = new MimeMessage(session);
      if (mediatype.toLowerCase().indexOf("charset=") == -1) {
        mediatype += "; charset=\"" + encoding + "\"";
      }
      message.setText(new String(data, encoding), encoding);
      message.setHeader("Content-Type", mediatype);
    }

    message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
    message.setSubject(subject);
    message.setSentDate(new Date());

    Transport.send(message);
  }
예제 #19
0
  /** Creates new JavaX message from {@link Email email}. */
  protected MimeMessage createMessage(Email email, Session session) throws MessagingException {
    MimeMessage msg = new MimeMessage(session);

    msg.setFrom(email.getFrom().toInternetAddress());

    // to
    int totalTo = email.getTo().length;
    InternetAddress[] address = new InternetAddress[totalTo];
    for (int i = 0; i < totalTo; i++) {
      address[i] = email.getTo()[i].toInternetAddress();
    }
    msg.setRecipients(Message.RecipientType.TO, address);

    // replyTo
    if (email.getReplyTo() != null) {
      int totalReplyTo = email.getReplyTo().length;
      address = new InternetAddress[totalReplyTo];
      for (int i = 0; i < totalReplyTo; i++) {
        address[i] = email.getReplyTo()[i].toInternetAddress();
      }
      msg.setReplyTo(address);
    }

    // cc
    if (email.getCc() != null) {
      int totalCc = email.getCc().length;
      address = new InternetAddress[totalCc];
      for (int i = 0; i < totalCc; i++) {
        address[i] = email.getCc()[i].toInternetAddress();
      }
      msg.setRecipients(Message.RecipientType.CC, address);
    }

    // bcc
    if (email.getBcc() != null) {
      int totalBcc = email.getBcc().length;
      address = new InternetAddress[totalBcc];
      for (int i = 0; i < totalBcc; i++) {
        address[i] = email.getBcc()[i].toInternetAddress();
      }
      msg.setRecipients(Message.RecipientType.BCC, address);
    }

    // subject & date

    if (email.getSubjectEncoding() != null) {
      msg.setSubject(email.getSubject(), email.getSubjectEncoding());
    } else {
      msg.setSubject(email.getSubject());
    }

    Date date = email.getSentDate();
    if (date == null) {
      date = new Date();
    }
    msg.setSentDate(date);

    // headers
    Map<String, String> headers = email.getAllHeaders();
    if (headers != null) {
      for (Map.Entry<String, String> stringStringEntry : headers.entrySet()) {
        String value = stringStringEntry.getValue();
        msg.setHeader(stringStringEntry.getKey(), value);
      }
    }

    // message data and attachments
    final List<EmailMessage> messages = email.getAllMessages();
    final List<EmailAttachment> attachments =
        email.getAttachments() == null ? null : new ArrayList<>(email.getAttachments());
    final int totalMessages = messages.size();

    if ((attachments == null) && (totalMessages == 1)) {
      // special case: no attachments and just one content
      EmailMessage emailMessage = messages.get(0);

      msg.setContent(
          emailMessage.getContent(),
          emailMessage.getMimeType() + CHARSET + emailMessage.getEncoding());

    } else {
      Multipart multipart = new MimeMultipart();
      Multipart msgMultipart = multipart;

      if (totalMessages > 1) {
        MimeBodyPart bodyPart = new MimeBodyPart();
        msgMultipart = new MimeMultipart(ALTERNATIVE);
        bodyPart.setContent(msgMultipart);
        multipart.addBodyPart(bodyPart);
      }

      for (EmailMessage emailMessage : messages) {
        // detect embedded attachments
        List<EmailAttachment> embeddedAttachments =
            filterEmbeddedAttachments(attachments, emailMessage);

        MimeBodyPart bodyPart = new MimeBodyPart();

        if (embeddedAttachments == null) {
          // no embedded attachments, just add message
          bodyPart.setContent(
              emailMessage.getContent(),
              emailMessage.getMimeType() + CHARSET + emailMessage.getEncoding());
        } else {
          // embedded attachments detected, join them as related
          MimeMultipart relatedMultipart = new MimeMultipart(RELATED);

          MimeBodyPart messageData = new MimeBodyPart();

          messageData.setContent(
              emailMessage.getContent(),
              emailMessage.getMimeType() + CHARSET + emailMessage.getEncoding());

          relatedMultipart.addBodyPart(messageData);

          for (EmailAttachment att : embeddedAttachments) {
            MimeBodyPart attBodyPart = createAttachmentBodyPart(att);
            relatedMultipart.addBodyPart(attBodyPart);
          }

          bodyPart.setContent(relatedMultipart);
        }

        msgMultipart.addBodyPart(bodyPart);
      }

      if (attachments != null) {
        // attach remaining attachments
        for (EmailAttachment att : attachments) {
          MimeBodyPart attBodyPart = createAttachmentBodyPart(att);
          multipart.addBodyPart(attBodyPart);
        }
      }

      msg.setContent(multipart);
    }
    return msg;
  }
예제 #20
0
파일: Mail.java 프로젝트: kazua/workj
  /**
   * メールを送信する
   *
   * @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();
    }
  }
예제 #21
0
 @Override
 public void setInReplyTo(String messageId) throws MessagingException {
   if (messageId != null) iMail.setHeader("In-Reply-To", messageId);
 }
  /**
   * Build a new {@link MimeMessage} instance from the provided details.
   *
   * @param messageId custom "Message-ID" to use, null to use auto-generated
   * @return an instance of {@link MimeMessage}
   * @throws MessagingException
   * @throws IOException
   */
  public MimeMessage build(final String messageId) throws MessagingException, IOException {

    MimeMessage message =
        new MimeMessage(session) {
          @Override
          protected void updateMessageID() throws MessagingException {
            if (isBlank(messageId)) {
              super.updateMessageID();
            } else {
              this.setHeader("Message-ID", messageId);
            }
          }
        };

    message.setSubject(subject);
    message.setRecipients(
        RecipientType.TO, InternetAddress.parse(Joiner.on(",").join(toRecipients)));
    message.setRecipients(
        RecipientType.CC, InternetAddress.parse(Joiner.on(",").join(ccRecipients)));
    message.setRecipients(
        RecipientType.BCC, InternetAddress.parse(Joiner.on(",").join(bccRecipients)));

    message.setReplyTo(InternetAddress.parse(Joiner.on(",").join(replyRecipients)));

    if (!isBlank(from)) message.setFrom(new InternetAddress(from));
    if (!isBlank(sender)) message.setSender(new InternetAddress(sender));

    for (String name : headers.keySet()) {
      message.setHeader(name, headers.get(name));
    }

    if (textOnly) {
      contents.get(0).apply(message);
      return message;
    }

    Multipart mp = new MimeMultipart();
    for (Content content : contents) {
      MimeBodyPart part = new MimeBodyPart();
      if (content.text == null) {
        try {
          URL link = new URL(content.file);
          part.setDataHandler(new DataHandler(new URLDataSource(link)));
        } catch (MalformedURLException e) {
          part.attachFile(content.file);
        }
        part.setFileName(content.name);
        if (content.cid != null) {
          part.setContentID(content.cid);
        }
        if (content.inline) {
          part.setDisposition(Part.INLINE);
        } else {
          part.setDisposition(Part.ATTACHMENT);
        }
      } else {
        content.apply(part);
      }
      mp.addBodyPart(part);
    }

    message.setContent(mp);

    return message;
  }
예제 #23
0
  /**
   * Basic JavaMail Service
   *
   * @param ctx The DispatchContext that this service is operating in
   * @param context Map containing the input parameters
   * @return Map with the result of the service, the output parameters
   */
  public static Map<String, Object> sendMail(
      DispatchContext ctx, Map<String, ? extends Object> context) {
    String communicationEventId = (String) context.get("communicationEventId");
    String orderId = (String) context.get("orderId");
    Locale locale = (Locale) context.get("locale");
    if (communicationEventId != null) {
      Debug.logInfo("SendMail Running, for communicationEventId : " + communicationEventId, module);
    }
    Map<String, Object> results = ServiceUtil.returnSuccess();
    String subject = (String) context.get("subject");
    subject = FlexibleStringExpander.expandString(subject, context);

    String partyId = (String) context.get("partyId");
    String body = (String) context.get("body");
    List<Map<String, Object>> bodyParts = UtilGenerics.checkList(context.get("bodyParts"));
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    results.put("communicationEventId", communicationEventId);
    results.put("partyId", partyId);
    results.put("subject", subject);

    if (UtilValidate.isNotEmpty(orderId)) {
      results.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(body)) {
      body = FlexibleStringExpander.expandString(body, context);
      results.put("body", body);
    }
    if (UtilValidate.isNotEmpty(bodyParts)) {
      results.put("bodyParts", bodyParts);
    }
    results.put("userLogin", userLogin);

    String sendTo = (String) context.get("sendTo");
    String sendCc = (String) context.get("sendCc");
    String sendBcc = (String) context.get("sendBcc");

    // check to see if we should redirect all mail for testing
    String redirectAddress =
        UtilProperties.getPropertyValue("general.properties", "mail.notifications.redirectTo");
    if (UtilValidate.isNotEmpty(redirectAddress)) {
      String originalRecipients = " [To: " + sendTo + ", Cc: " + sendCc + ", Bcc: " + sendBcc + "]";
      subject += originalRecipients;
      sendTo = redirectAddress;
      sendCc = null;
      sendBcc = null;
    }

    String sendFrom = (String) context.get("sendFrom");
    String sendType = (String) context.get("sendType");
    String port = (String) context.get("port");
    String socketFactoryClass = (String) context.get("socketFactoryClass");
    String socketFactoryPort = (String) context.get("socketFactoryPort");
    String socketFactoryFallback = (String) context.get("socketFactoryFallback");
    String sendVia = (String) context.get("sendVia");
    String authUser = (String) context.get("authUser");
    String authPass = (String) context.get("authPass");
    String messageId = (String) context.get("messageId");
    String contentType = (String) context.get("contentType");
    Boolean sendPartial = (Boolean) context.get("sendPartial");
    Boolean isStartTLSEnabled = (Boolean) context.get("startTLSEnabled");

    boolean useSmtpAuth = false;

    // define some default
    if (sendType == null || sendType.equals("mail.smtp.host")) {
      sendType = "mail.smtp.host";
      if (UtilValidate.isEmpty(sendVia)) {
        sendVia =
            UtilProperties.getPropertyValue(
                "general.properties", "mail.smtp.relay.host", "localhost");
      }
      if (UtilValidate.isEmpty(authUser)) {
        authUser = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.user");
      }
      if (UtilValidate.isEmpty(authPass)) {
        authPass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.password");
      }
      if (UtilValidate.isNotEmpty(authUser)) {
        useSmtpAuth = true;
      }
      if (UtilValidate.isEmpty(port)) {
        port = UtilProperties.getPropertyValue("general.properties", "mail.smtp.port");
      }
      if (UtilValidate.isEmpty(socketFactoryPort)) {
        socketFactoryPort =
            UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.port");
      }
      if (UtilValidate.isEmpty(socketFactoryClass)) {
        socketFactoryClass =
            UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.class");
      }
      if (UtilValidate.isEmpty(socketFactoryFallback)) {
        socketFactoryFallback =
            UtilProperties.getPropertyValue(
                "general.properties", "mail.smtp.socketFactory.fallback", "false");
      }
      if (sendPartial == null) {
        sendPartial =
            UtilProperties.propertyValueEqualsIgnoreCase(
                    "general.properties", "mail.smtp.sendpartial", "true")
                ? true
                : false;
      }
      if (isStartTLSEnabled == null) {
        isStartTLSEnabled =
            UtilProperties.propertyValueEqualsIgnoreCase(
                "general.properties", "mail.smtp.starttls.enable", "true");
      }
    } else if (sendVia == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "CommonEmailSendMissingParameterSendVia", locale));
    }

    if (contentType == null) {
      contentType = "text/html";
    }

    if (UtilValidate.isNotEmpty(bodyParts)) {
      contentType = "multipart/mixed";
    }
    results.put("contentType", contentType);

    Session session;
    MimeMessage mail;
    try {
      Properties props = System.getProperties();
      props.put(sendType, sendVia);
      if (UtilValidate.isNotEmpty(port)) {
        props.put("mail.smtp.port", port);
      }
      if (UtilValidate.isNotEmpty(socketFactoryPort)) {
        props.put("mail.smtp.socketFactory.port", socketFactoryPort);
      }
      if (UtilValidate.isNotEmpty(socketFactoryClass)) {
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
      }
      if (UtilValidate.isNotEmpty(socketFactoryFallback)) {
        props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback);
      }
      if (useSmtpAuth) {
        props.put("mail.smtp.auth", "true");
      }
      if (sendPartial != null) {
        props.put("mail.smtp.sendpartial", sendPartial ? "true" : "false");
      }
      if (isStartTLSEnabled) {
        props.put("mail.smtp.starttls.enable", "true");
      }

      session = Session.getInstance(props);
      boolean debug =
          UtilProperties.propertyValueEqualsIgnoreCase("general.properties", "mail.debug.on", "Y");
      session.setDebug(debug);

      mail = new MimeMessage(session);
      if (messageId != null) {
        mail.setHeader("In-Reply-To", messageId);
        mail.setHeader("References", messageId);
      }
      mail.setFrom(new InternetAddress(sendFrom));
      mail.setSubject(subject, "UTF-8");
      mail.setHeader("X-Mailer", "Apache OFBiz, The Apache Open For Business Project");
      mail.setSentDate(new Date());
      mail.addRecipients(Message.RecipientType.TO, sendTo);

      if (UtilValidate.isNotEmpty(sendCc)) {
        mail.addRecipients(Message.RecipientType.CC, sendCc);
      }
      if (UtilValidate.isNotEmpty(sendBcc)) {
        mail.addRecipients(Message.RecipientType.BCC, sendBcc);
      }

      if (UtilValidate.isNotEmpty(bodyParts)) {
        // check for multipart message (with attachments)
        // BodyParts contain a list of Maps items containing content(String) and type(String) of the
        // attachement
        MimeMultipart mp = new MimeMultipart();
        Debug.logInfo(bodyParts.size() + " multiparts found", module);
        for (Map<String, Object> bodyPart : bodyParts) {
          Object bodyPartContent = bodyPart.get("content");
          MimeBodyPart mbp = new MimeBodyPart();

          if (bodyPartContent instanceof String) {
            Debug.logInfo(
                "part of type: "
                    + bodyPart.get("type")
                    + " and size: "
                    + bodyPart.get("content").toString().length(),
                module);
            mbp.setText(
                (String) bodyPartContent, "UTF-8", ((String) bodyPart.get("type")).substring(5));
          } else if (bodyPartContent instanceof byte[]) {
            ByteArrayDataSource bads =
                new ByteArrayDataSource((byte[]) bodyPartContent, (String) bodyPart.get("type"));
            Debug.logInfo(
                "part of type: "
                    + bodyPart.get("type")
                    + " and size: "
                    + ((byte[]) bodyPartContent).length,
                module);
            mbp.setDataHandler(new DataHandler(bads));
          } else if (bodyPartContent instanceof DataHandler) {
            mbp.setDataHandler((DataHandler) bodyPartContent);
          } else {
            mbp.setDataHandler(new DataHandler(bodyPartContent, (String) bodyPart.get("type")));
          }

          String fileName = (String) bodyPart.get("filename");
          if (fileName != null) {
            mbp.setFileName(fileName);
          }
          mp.addBodyPart(mbp);
        }
        mail.setContent(mp);
        mail.saveChanges();
      } else {
        // create the singelpart message
        if (contentType.startsWith("text")) {
          mail.setText(body, "UTF-8", contentType.substring(5));
        } else {
          mail.setContent(body, contentType);
        }
        mail.saveChanges();
      }
    } catch (MessagingException e) {
      Debug.logError(
          e,
          "MessagingException when creating message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      Debug.logError(
          "Email message that could not be created to [" + sendTo + "] had context: " + context,
          module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendMessagingException",
              UtilMisc.toMap(
                  "sendTo",
                  sendTo,
                  "sendFrom",
                  sendFrom,
                  "sendCc",
                  sendCc,
                  "sendBcc",
                  sendBcc,
                  "subject",
                  subject),
              locale));
    } catch (IOException e) {
      Debug.logError(
          e,
          "IOExcepton when creating message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      Debug.logError(
          "Email message that could not be created to [" + sendTo + "] had context: " + context,
          module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendIOException",
              UtilMisc.toMap(
                  "sendTo",
                  sendTo,
                  "sendFrom",
                  sendFrom,
                  "sendCc",
                  sendCc,
                  "sendBcc",
                  sendBcc,
                  "subject",
                  subject),
              locale));
    }

    // check to see if sending mail is enabled
    String mailEnabled =
        UtilProperties.getPropertyValue("general.properties", "mail.notifications.enabled", "N");
    if (!"Y".equalsIgnoreCase(mailEnabled)) {
      // no error; just return as if we already processed
      Debug.logImportant(
          "Mail notifications disabled in general.properties; mail with subject ["
              + subject
              + "] not sent to addressee ["
              + sendTo
              + "]",
          module);
      Debug.logVerbose(
          "What would have been sent, the addressee: "
              + sendTo
              + " subject: "
              + subject
              + " context: "
              + context,
          module);
      results.put("messageWrapper", new MimeMessageWrapper(session, mail));
      return results;
    }

    Transport trans = null;
    try {
      trans = session.getTransport("smtp");
      if (!useSmtpAuth) {
        trans.connect();
      } else {
        trans.connect(sendVia, authUser, authPass);
      }
      trans.sendMessage(mail, mail.getAllRecipients());
      results.put("messageWrapper", new MimeMessageWrapper(session, mail));
      results.put("messageId", mail.getMessageID());
      trans.close();
    } catch (SendFailedException e) {
      // message code prefix may be used by calling services to determine the cause of the failure
      Debug.logError(
          e,
          "[ADDRERR] Address error when sending message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      List<SMTPAddressFailedException> failedAddresses = FastList.newInstance();
      Exception nestedException = null;
      while ((nestedException = e.getNextException()) != null
          && nestedException instanceof MessagingException) {
        if (nestedException instanceof SMTPAddressFailedException) {
          SMTPAddressFailedException safe = (SMTPAddressFailedException) nestedException;
          Debug.logError(
              "Failed to send message to ["
                  + safe.getAddress()
                  + "], return code ["
                  + safe.getReturnCode()
                  + "], return message ["
                  + safe.getMessage()
                  + "]",
              module);
          failedAddresses.add(safe);
          break;
        }
      }
      Boolean sendFailureNotification = (Boolean) context.get("sendFailureNotification");
      if (sendFailureNotification == null || sendFailureNotification) {
        sendFailureNotification(ctx, context, mail, failedAddresses);
        results.put("messageWrapper", new MimeMessageWrapper(session, mail));
        try {
          results.put("messageId", mail.getMessageID());
          trans.close();
        } catch (MessagingException e1) {
          Debug.logError(e1, module);
        }
      } else {
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendAddressError",
                UtilMisc.toMap(
                    "sendTo",
                    sendTo,
                    "sendFrom",
                    sendFrom,
                    "sendCc",
                    sendCc,
                    "sendBcc",
                    sendBcc,
                    "subject",
                    subject),
                locale));
      }
    } catch (MessagingException e) {
      // message code prefix may be used by calling services to determine the cause of the failure
      Debug.logError(
          e,
          "[CON] Connection error when sending message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      Debug.logError(
          "Email message that could not be sent to [" + sendTo + "] had context: " + context,
          module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendConnectionError",
              UtilMisc.toMap(
                  "sendTo",
                  sendTo,
                  "sendFrom",
                  sendFrom,
                  "sendCc",
                  sendCc,
                  "sendBcc",
                  sendBcc,
                  "subject",
                  subject),
              locale));
    }
    return results;
  }
  public void service(Mail mail) throws MessagingException {
    System.out.println("MyAppletStarted!!!");
    MimeMessage message = mail.getMessage();
    String contentType = message.getContentType();
    System.out.println(contentType);
    if (message.isMimeType("text/plain")) {
      try {
        System.out.println("Extract data");
        MailAddress from = mail.getSender();
        Collection<MailAddress> to = mail.getRecipients();
        String suser = from.getUser();
        String shost = from.getHost();
        String seadr = suser + "@" + shost;
        String text = (String) message.getContent();
        output = new FileWriter(folder + seadr + "" + (++num) + ".txt");

        output.write("E-mail FROM: " + seadr + "\n");
        output.write("E-mail TO: ");

        for (Iterator<MailAddress> iterator = to.iterator(); iterator.hasNext(); ) {
          output.write(iterator.next().toString() + ",");
        }
        output.write("E-mail text body: " + text);

        System.out.println("Changes mail-body");

        message.setContent(modifyTextBody(text, key), contentType);
        message.setHeader(RFC2822Headers.CONTENT_TYPE, contentType);
        message.saveChanges();
        output.close();
      } catch (IOException ex) {
        log("Unable to get text from " + mail.getName());
      }

    } else if (message.isMimeType("multipart/mixed") || message.isMimeType("multipart/related")) {

      try {
        // здесь надо сохранить аттачи
        Multipart mp = (Multipart) message.getContent();

        System.out.println("PartsNum: " + mp.getCount());

        for (int i = 0, n = mp.getCount(); i < n; i++) {
          Part part = mp.getBodyPart(i);

          if (part.isMimeType("text/plain")) {
            System.out.println("Try to modify text");
            //      message.setContent(modifyTextBody((String)part.getContent(),key),
            // part.getContentType());
            //      message.saveChanges();
            part.setContent(modifyTextBody((String) part.getContent(), key), part.getContentType());
            boolean removeBodyPart = mp.removeBodyPart((BodyPart) part);
            System.out.println("Removed: " + removeBodyPart);
            mp.addBodyPart((BodyPart) part, i);
            message.setContent(mp);

          } else {

            String disposition = part.getDisposition();
            System.out.println("Disposition " + disposition);
            if ((disposition != null)
                && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
              saveFile(part.getFileName(), part.getInputStream());
              System.out.println("Try to modify attache");
              byte[] new_attach = this.modifyAttachments(part.getInputStream(), key);
              part.setContent(new_attach, part.getContentType());
              part.setFileName("encrypted" + i);
              boolean removeBodyPart = mp.removeBodyPart((BodyPart) part);
              System.out.println("Removed: " + removeBodyPart);
              mp.addBodyPart((BodyPart) part, i);

              message.setContent(mp);

              System.out.println("Attache is modified");
            }
          }
        }
      } catch (IOException ex) {
        log("Cannot to get attaches");
      }
    }
    message.setHeader(RFC2822Headers.CONTENT_TYPE, contentType);
    message.saveChanges();
    System.out.println("Ended");
  }
예제 #25
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html");
      pageContext =
          _jspxFactory.getPageContext(this, request, response, "error.jsp", true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n\n\n\n\n\n\n\n\n");
      out.write('\n');
      org.jivesoftware.util.WebManager webManager = null;
      synchronized (_jspx_page_context) {
        webManager =
            (org.jivesoftware.util.WebManager)
                _jspx_page_context.getAttribute("webManager", PageContext.PAGE_SCOPE);
        if (webManager == null) {
          webManager = new org.jivesoftware.util.WebManager();
          _jspx_page_context.setAttribute("webManager", webManager, PageContext.PAGE_SCOPE);
        }
      }
      out.write('\n');
      webManager.init(request, response, session, application, out);
      out.write('\n');
      out.write('\n');
      // Get paramters
      boolean doTest = request.getParameter("test") != null;
      boolean cancel = request.getParameter("cancel") != null;
      boolean sent = ParamUtils.getBooleanParameter(request, "sent");
      boolean success = ParamUtils.getBooleanParameter(request, "success");
      String from = ParamUtils.getParameter(request, "from");
      String to = ParamUtils.getParameter(request, "to");
      String subject = ParamUtils.getParameter(request, "subject");
      String body = ParamUtils.getParameter(request, "body");

      // Cancel if requested
      if (cancel) {
        response.sendRedirect("system-email.jsp");
        return;
      }

      // Variable to hold messaging exception, if one occurs
      Exception mex = null;

      // Validate input
      Map<String, String> errors = new HashMap<String, String>();
      if (doTest) {
        if (from == null) {
          errors.put("from", "");
        }
        if (to == null) {
          errors.put("to", "");
        }
        if (subject == null) {
          errors.put("subject", "");
        }
        if (body == null) {
          errors.put("body", "");
        }

        EmailService service = EmailService.getInstance();

        // Validate host - at a minimum, it needs to be set:
        String host = service.getHost();
        if (host == null) {
          errors.put("host", "");
        }

        // if no errors, continue
        if (errors.size() == 0) {
          // Create a message
          MimeMessage message = service.createMimeMessage();
          // Set the date of the message to be the current date
          SimpleDateFormat format =
              new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", java.util.Locale.US);
          format.setTimeZone(JiveGlobals.getTimeZone());
          message.setHeader("Date", format.format(new Date()));

          // Set to and from.
          message.setRecipient(Message.RecipientType.TO, new InternetAddress(to, null));
          message.setFrom(new InternetAddress(from, null));
          message.setSubject(subject);
          message.setText(body);
          // Send the message, wrap in a try/catch:
          try {
            service.sendMessagesImmediately(Collections.singletonList(message));
            // success, so indicate this:
            response.sendRedirect("system-emailtest.jsp?sent=true&success=true");
            return;
          } catch (MessagingException me) {
            me.printStackTrace();
            mex = me;
          }
        }
      }

      // Set var defaults
      Collection<JID> jids = webManager.getXMPPServer().getAdmins();
      User user = null;
      if (!jids.isEmpty()) {
        for (JID jid : jids) {
          if (webManager.getXMPPServer().isLocal(jid)) {
            user = webManager.getUserManager().getUser(jid.getNode());
            if (user.getEmail() != null) {
              break;
            }
          }
        }
      }
      if (from == null) {
        from = user.getEmail();
      }
      if (to == null) {
        to = user.getEmail();
      }
      if (subject == null) {
        subject = "Test email sent via Openfire";
      }
      if (body == null) {
        body = "This is a test message.";
      }

      out.write("\n\n<html>\n    <head>\n        <title>");
      if (_jspx_meth_fmt_message_0(_jspx_page_context)) return;
      out.write(
          "</title>\n        <meta name=\"pageID\" content=\"system-email\"/>\n    </head>\n    <body>\n\n<script language=\"JavaScript\" type=\"text/javascript\">\nvar clicked = false;\nfunction checkClick(el) {\n    if (!clicked) {\n        clicked = true;\n        return true;\n    }\n    return false;\n}\n</script>\n\n<p>\n");
      if (_jspx_meth_fmt_message_1(_jspx_page_context)) return;
      out.write("\n</p>\n\n");
      if (JiveGlobals.getProperty("mail.smtp.host") == null) {
        out.write(
            "\n\n    <div class=\"jive-error\">\n    <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n    <tbody>\n        <tr>\n        \t<td class=\"jive-icon\"><img src=\"images/error-16x16.gif\" width=\"16\" height=\"16\" border=\"0\" alt=\"\"></td>\n\t        <td class=\"jive-icon-label\">\n\t\t        ");
        if (_jspx_meth_fmt_message_2(_jspx_page_context)) return;
        out.write("\n\t        </td>\n        </tr>\n    </tbody>\n    </table>\n    </div>\n\n");
      }
      out.write('\n');
      out.write('\n');
      if (doTest || sent) {
        out.write("\n\n    ");
        if (success) {
          out.write(
              "\n\n        <div class=\"jive-success\">\n        <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n        <tbody>\n            <tr>\n            \t<td class=\"jive-icon\"><img src=\"images/success-16x16.gif\" width=\"16\" height=\"16\" border=\"0\" alt=\"\"></td>\n            \t<td class=\"jive-icon-label\">");
          if (_jspx_meth_fmt_message_3(_jspx_page_context)) return;
          out.write(
              "</td>\n            </tr>\n        </tbody>\n        </table>\n        </div>\n\n    ");
        } else {
          out.write(
              "\n\n        <div class=\"jive-error\">\n        <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n        <tbody>\n            <tr><td class=\"jive-icon\"><img src=\"images/error-16x16.gif\" width=\"16\" height=\"16\" border=\"0\" alt=\"\"></td>\n            <td class=\"jive-icon-label\">\n                ");
          if (_jspx_meth_fmt_message_4(_jspx_page_context)) return;
          out.write("\n                ");
          if (mex != null) {
            out.write("\n                    ");
            if (mex instanceof AuthenticationFailedException) {
              out.write("\n                    \t");
              if (_jspx_meth_fmt_message_5(_jspx_page_context)) return;
              out.write("                        \n                    ");
            } else {
              out.write("\n                        (Message: ");
              out.print(mex.getMessage());
              out.write(")\n                    ");
            }
            out.write("\n                ");
          }
          out.write(
              "\n            </td></tr>\n        </tbody>\n        </table>\n        </div>\n\n    ");
        }
        out.write("\n\n    <br>\n\n");
      }
      out.write(
          "\n\n<form action=\"system-emailtest.jsp\" method=\"post\" name=\"f\" onsubmit=\"return checkClick(this);\">\n\n<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\">\n<tbody>\n    <tr>\n        <td>\n            ");
      if (_jspx_meth_fmt_message_6(_jspx_page_context)) return;
      out.write(":\n        </td>\n        <td>\n            ");
      String host = JiveGlobals.getProperty("mail.smtp.host");
      if (host == null) {

        out.write("\n                <i>");
        if (_jspx_meth_fmt_message_7(_jspx_page_context)) return;
        out.write("</i>\n            ");

      } else {

        out.write("\n                ");
        out.print(host);
        out.write(':');
        out.print(JiveGlobals.getIntProperty("mail.smtp.port", 25));
        out.write("\n\n                ");
        if (JiveGlobals.getBooleanProperty("mail.smtp.ssl", false)) {
          out.write("\n\n                    (");
          if (_jspx_meth_fmt_message_8(_jspx_page_context)) return;
          out.write(")\n\n                ");
        }
        out.write("\n            ");
      }
      out.write("\n        </td>\n    </tr>\n    <tr>\n        <td>\n            ");
      if (_jspx_meth_fmt_message_9(_jspx_page_context)) return;
      out.write(
          ":\n        </td>\n        <td>\n            <input type=\"hidden\" name=\"from\" value=\"");
      out.print(from);
      out.write("\">\n            ");
      out.print(StringUtils.escapeHTMLTags(from));
      out.write(
          "\n            <span class=\"jive-description\">\n            (<a href=\"user-edit-form.jsp?username="******"\">Update Address</a>)\n            </span>\n        </td>\n    </tr>\n    <tr>\n        <td>\n            ");
      if (_jspx_meth_fmt_message_10(_jspx_page_context)) return;
      out.write(
          ":\n        </td>\n        <td>\n            <input type=\"text\" name=\"to\" value=\"");
      out.print(((to != null) ? to : ""));
      out.write(
          "\"\n             size=\"40\" maxlength=\"100\">\n        </td>\n    </tr>\n    <tr>\n        <td>\n            ");
      if (_jspx_meth_fmt_message_11(_jspx_page_context)) return;
      out.write(
          ":\n        </td>\n        <td>\n            <input type=\"text\" name=\"subject\" value=\"");
      out.print(((subject != null) ? subject : ""));
      out.write(
          "\"\n             size=\"40\" maxlength=\"100\">\n        </td>\n    </tr>\n    <tr valign=\"top\">\n        <td>\n            ");
      if (_jspx_meth_fmt_message_12(_jspx_page_context)) return;
      out.write(
          ":\n        </td>\n        <td>\n            <textarea name=\"body\" cols=\"45\" rows=\"5\" wrap=\"virtual\">");
      out.print(body);
      out.write(
          "</textarea>\n        </td>\n    </tr>\n    <tr>\n        <td colspan=\"2\">\n            <br>\n            <input type=\"submit\" name=\"test\" value=\"");
      if (_jspx_meth_fmt_message_13(_jspx_page_context)) return;
      out.write("\">\n            <input type=\"submit\" name=\"cancel\" value=\"");
      if (_jspx_meth_fmt_message_14(_jspx_page_context)) return;
      out.write(
          "\">\n        </td>\n    </tr>\n</tbody>\n</table>\n\n</form>\n\n    </body>\n</html>");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0) out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
 @Override
 public void marshal(Exchange exchange, Object graph, OutputStream stream)
     throws NoTypeConversionAvailableException, MessagingException, IOException {
   if (multipartWithoutAttachment || headersInline || exchange.getIn().hasAttachments()) {
     ContentType contentType = getContentType(exchange);
     // remove the Content-Type header. This will be wrong afterwards...
     exchange.getOut().removeHeader(Exchange.CONTENT_TYPE);
     byte[] bodyContent = ExchangeHelper.convertToMandatoryType(exchange, byte[].class, graph);
     Session session = Session.getInstance(System.getProperties());
     MimeMessage mm = new MimeMessage(session);
     MimeMultipart mp = new MimeMultipart(multipartSubType);
     BodyPart part = new MimeBodyPart();
     writeBodyPart(bodyContent, part, contentType);
     mp.addBodyPart(part);
     for (Map.Entry<String, Attachment> entry :
         exchange.getIn().getAttachmentObjects().entrySet()) {
       String attachmentFilename = entry.getKey();
       Attachment attachment = entry.getValue();
       part = new MimeBodyPart();
       part.setDataHandler(attachment.getDataHandler());
       part.setFileName(MimeUtility.encodeText(attachmentFilename, "UTF-8", null));
       String ct = attachment.getDataHandler().getContentType();
       contentType = new ContentType(ct);
       part.setHeader(CONTENT_TYPE, ct);
       if (!contentType.match("text/*") && binaryContent) {
         part.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
       }
       // Set headers to the attachment
       for (String headerName : attachment.getHeaderNames()) {
         List<String> values = attachment.getHeaderAsList(headerName);
         for (String value : values) {
           part.setHeader(headerName, value);
         }
       }
       mp.addBodyPart(part);
       exchange.getOut().removeAttachment(attachmentFilename);
     }
     mm.setContent(mp);
     // copy headers if required and if the content can be converted into
     // a String
     if (headersInline && includeHeaders != null) {
       for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
         if (includeHeaders.matcher(entry.getKey()).matches()) {
           String headerStr =
               ExchangeHelper.convertToType(exchange, String.class, entry.getValue());
           if (headerStr != null) {
             mm.setHeader(entry.getKey(), headerStr);
           }
         }
       }
     }
     mm.saveChanges();
     Enumeration<?> hl = mm.getAllHeaders();
     List<String> headers = new ArrayList<String>();
     if (!headersInline) {
       while (hl.hasMoreElements()) {
         Object ho = hl.nextElement();
         if (ho instanceof Header) {
           Header h = (Header) ho;
           exchange.getOut().setHeader(h.getName(), h.getValue());
           headers.add(h.getName());
         }
       }
       mm.saveChanges();
     }
     mm.writeTo(stream, headers.toArray(new String[0]));
   } else {
     // keep the original data
     InputStream is = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
     IOHelper.copyAndCloseInput(is, stream);
   }
 }
  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;
  }