private static void sendMimeMessage(
      String from,
      String to,
      String subject,
      String content,
      List<String> filenames,
      Session session) {

    try {
      String[] toArr = {to};
      DataSource[] attachments = (filenames == null) ? null : new DataSource[filenames.size()];

      if (filenames != null) {
        int i = 0;
        for (String filename : filenames) {
          attachments[i++] = new FileDataSource(filename);
        }
      }

      MimeMessage message = createMimeMessage(session, from, toArr, subject, content, attachments);
      message.saveChanges();

      Transport transport = session.getTransport();
      try {
        transport.connect();
        transport.sendMessage(message, message.getAllRecipients());
      } finally {
        transport.close();
      }
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
  public void enviarEmail() {
    FacesContext context = FacesContext.getCurrentInstance();
    AutenticaUsuario autenticaUsuario =
        new AutenticaUsuario(GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL);
    Session session = Session.getDefaultInstance(this.configuracaoEmail(), autenticaUsuario);
    session.setDebug(true);

    try {

      Transport envio = null;
      MimeMessage email = new MimeMessage(session);
      email.setRecipient(Message.RecipientType.TO, new InternetAddress(this.para));
      email.setFrom(new InternetAddress(this.de));
      email.setSubject(this.assunto);
      email.setContent(this.mensagem, "text/plain");
      email.setSentDate(new Date());
      envio = session.getTransport("smtp");
      envio.connect(GmailBean.SERVIDOR_SMTP, GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL);
      email.saveChanges();
      envio.sendMessage(email, email.getAllRecipients());
      envio.close();

      context.addMessage(null, new FacesMessage("E-mail enviado com sucesso"));

    } catch (AddressException e) {
      FacesMessage msg =
          new FacesMessage("Erro ao montar mensagem de e-mail! Erro: " + e.getMessage());
      context.addMessage(null, msg);
      return;
    } catch (MessagingException e) {
      FacesMessage msg = new FacesMessage("Erro ao enviar e-mail! Erro: " + e.getMessage());
      context.addMessage(null, msg);
      return;
    }
  }
  /** 发�?邮件 */
  public boolean sendOut() {
    try {
      mimeMsg.setContent(mp);
      mimeMsg.saveChanges();
      System.out.println("正在发�?邮件....");

      Session mailSession = Session.getInstance(props, null);
      Transport transport = mailSession.getTransport("smtp");
      transport.connect((String) props.get("mail.smtp.host"), username, password);
      transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
      //          如果抄�?人为null  不添加抄送人
      if (mimeMsg.getRecipients(Message.RecipientType.CC) != null)
        transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
      // transport.send(mimeMsg);

      System.out.println("发送邮件成功");
      transport.close();

      return true;
    } catch (Exception e) {
      System.err.println("邮件发送失败" + e);
      e.printStackTrace();
      return false;
    }
  }
Exemple #4
0
 @Override
 public void send() throws MessagingException, UnsupportedEncodingException {
   long t0 = System.currentTimeMillis();
   try {
     if (iMail.getFrom() == null || iMail.getFrom().length == 0)
       setFrom(
           ApplicationProperty.EmailSenderAddress.value(),
           ApplicationProperty.EmailSenderName.value());
     if (iMail.getReplyTo() == null || iMail.getReplyTo().length == 0)
       setReplyTo(
           ApplicationProperty.EmailReplyToAddress.value(),
           ApplicationProperty.EmailReplyToName.value());
     iMail.setSentDate(new Date());
     iMail.setContent(iBody);
     iMail.saveChanges();
     Transport.send(iMail);
   } finally {
     long t = System.currentTimeMillis() - t0;
     if (t > 30000)
       sLog.warn(
           "It took "
               + new DecimalFormat("0.00").format(t / 1000.0)
               + " seconds to send an email.");
     else if (t > 5000)
       sLog.info(
           "It took "
               + new DecimalFormat("0.00").format(t / 1000.0)
               + " seconds to send an email.");
   }
 }
  /** 根据传入的 Seesion 对象创建混合型的 MIME消息 */
  public MimeMessage createMessage(Session session) throws Exception {
    String from = "*****@*****.**";
    String to = "*****@*****.**";
    String subject = "创建内含附件、图文并茂的邮件!";
    String body =
        "<h4>内含附件、图文并茂的邮件测试!!!</h4> </br>"
            + "<a href = http://haolloyin.blog.51cto.com/> 蚂蚁</a></br>"
            + "<img src = \"cid:logo_jpg\"></a>";

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject(subject);

    // 创建邮件的各个 MimeBodyPart 部分
    MimeBodyPart attachment01 = createAttachment("F:\\java\\Snake.java");
    MimeBodyPart attachment02 = createAttachment("F:\\java\\meng.mp3");
    MimeBodyPart content = createContent(body, "F:\\java\\logo.jpg");

    // 将邮件中各个部分组合到一个"mixed"型的 MimeMultipart 对象
    MimeMultipart allPart = new MimeMultipart("mixed");
    allPart.addBodyPart(attachment01);
    allPart.addBodyPart(attachment02);
    allPart.addBodyPart(content);

    // 将上面混合型的 MimeMultipart 对象作为邮件内容并保存
    msg.setContent(allPart);
    msg.saveChanges();
    return msg;
  }
  @Override
  public final void pre_commit(boolean dirty) throws DataFault {

    /* All commits to this object forces a write back of the message
     * as it is hard to tell if the message has changed.
     *
     */
    hash = -1;
    try {
      if (m != null) {
        // StreamData sd = new MessageStreamData(m);
        StreamData sd = new ByteArrayStreamData();
        // can't call saveChanges on imported imap message
        if (auto_save) {
          m.saveChanges();
        }
        m.writeTo(sd.getOutputStream());
        // getLogger().debug("update value to "+sd);
        record.setProperty(MESSAGE, sd);
        m = null; // force re-read
      }
    } catch (Exception e) {
      getContext().error(e, "Error writing mail message");
    }
  }
 private MimeMessage getMockedMimeMessage() throws MessagingException {
   MimeMessage mockedMimeMessage = MailUtil.createMimeMessage();
   mockedMimeMessage.setHeader(HEADER1, "true");
   mockedMimeMessage.setHeader(HEADER2, "true");
   mockedMimeMessage.saveChanges();
   return mockedMimeMessage;
 }
  public static void main(String args[]) throws Exception {
    //
    // create the generator for creating an smime/compressed message
    //
    SMIMECompressedGenerator gen = new SMIMECompressedGenerator();

    //
    // create the base for our message
    //
    MimeBodyPart msg = new MimeBodyPart();

    msg.setText("Hello world!");

    MimeBodyPart mp = gen.generate(msg, new ZlibCompressor());

    //
    // Get a Session object and create the mail message
    //
    Properties props = System.getProperties();
    Session session = Session.getDefaultInstance(props, null);

    Address fromUser = new InternetAddress("\"Eric H. Echidna\"<*****@*****.**>");
    Address toUser = new InternetAddress("*****@*****.**");

    MimeMessage body = new MimeMessage(session);
    body.setFrom(fromUser);
    body.setRecipient(Message.RecipientType.TO, toUser);
    body.setSubject("example compressed message");
    body.setContent(mp.getContent(), mp.getContentType());
    body.saveChanges();

    body.writeTo(new FileOutputStream("compressed.message"));
  }
  public void testAttachments() throws Exception {
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "localhost");
    props.setProperty("mail.smtp.port", SMTP_PORT + "");
    Session session = Session.getInstance(props);

    MimeMessage baseMsg = new MimeMessage(session);
    MimeBodyPart bp1 = new MimeBodyPart();
    bp1.setHeader("Content-Type", "text/plain");
    bp1.setContent("Hello World!!!", "text/plain; charset=\"ISO-8859-1\"");

    // Attach the file
    MimeBodyPart bp2 = new MimeBodyPart();
    FileDataSource fileAttachment = new FileDataSource(BIGFILE_PATH);
    DataHandler dh = new DataHandler(fileAttachment);
    bp2.setDataHandler(dh);
    bp2.setFileName(fileAttachment.getName());

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(bp1);
    multipart.addBodyPart(bp2);

    baseMsg.setFrom(new InternetAddress("Ted <*****@*****.**>"));
    baseMsg.setRecipient(Message.RecipientType.TO, new InternetAddress("*****@*****.**"));
    baseMsg.setSubject("Test Big attached file message");
    baseMsg.setContent(multipart);
    baseMsg.saveChanges();

    LOG.debug("Send started");
    Transport t = new SMTPTransport(session, new URLName("smtp://*****:*****@example.org")});
    t.close();
    started = System.currentTimeMillis() - started;
    LOG.info("Elapsed ms = " + started);

    WiserMessage msg = server.getMessages().get(0);

    assertEquals(1, server.getMessages().size());
    assertEquals("*****@*****.**", msg.getEnvelopeReceiver());

    File compareFile = File.createTempFile("attached", ".tmp");
    LOG.debug("Writing received attachment ...");

    FileOutputStream fos = new FileOutputStream(compareFile);
    ((MimeMultipart) msg.getMimeMessage().getContent())
        .getBodyPart(1)
        .getDataHandler()
        .writeTo(fos);
    fos.close();
    LOG.debug("Checking integrity ...");
    assertTrue(checkIntegrity(new File(BIGFILE_PATH), compareFile));
    LOG.debug("Checking integrity DONE");
    compareFile.delete();
    msg.dispose();
  }
 /**
  * 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());
   }
 }
  public void sendEMailToUser(ICFSecuritySecUserObj toUser, String msgSubject, String msgBody)
      throws IOException, MessagingException, NamingException {

    final String S_ProcName = "sendEMailToUser";

    Properties props = System.getProperties();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFInternet25SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpEmailFrom");
    }

    smtpUsername = (String) ctx.lookup("java:comp/env/CFInternet25SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFInternet25SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpPassword");
    }

    Session emailSess =
        Session.getInstance(
            props,
            new Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
              }
            });

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(toUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject((msgSubject != null) ? msgSubject : "No subject");
    msg.setSentDate(new Date());
    msg.setContent(msgBody, "text/html");
    msg.saveChanges();

    Transport.send(msg);
  }
  @Test
  public void messageID() throws Exception {
    Provisioning prov = Provisioning.getInstance();
    Domain domain = prov.createDomain("example.com", new HashMap<String, Object>());
    Account account =
        prov.createAccount("*****@*****.**", "test123", new HashMap<String, Object>());

    MimeMessage mm = new MimeMessage(JMSession.getSmtpSession(account));
    mm.saveChanges();
    Assert.assertEquals(
        "message ID contains account domain",
        domain.getName() + '>',
        mm.getMessageID().split("@")[1]);
  }
 /**
  * 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;
 }
Exemple #14
0
  /**
   * Send an email over SMTP.
   *
   * @param _to recipient
   * @param _cc cc'd users
   * @param _bcc bcc'd users
   * @param _subject the subject
   * @param _file path to attachment
   * @param _message the message
   * @throws MessagingException the messaging exception
   */
  public void send(
      String _to, String _cc, String _bcc, String _subject, String _file, String _message)
      throws MessagingException {

    MimeMessage message = new MimeMessage(SESSION);

    message.setFrom(new InternetAddress(CONFIG.getProperty("mail.address")));

    message.setRecipients(Message.RecipientType.TO, _to);
    if (_cc.length() > 0) message.setRecipients(Message.RecipientType.CC, _cc);
    if (_bcc.length() > 0) message.setRecipients(Message.RecipientType.BCC, _bcc);

    message.setSubject(_subject);
    message.setText(_message);

    message.saveChanges();
    send(message);
  }
Exemple #15
0
  private Message createMessage(Session session, User user2) throws Exception {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(email));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
    message.setSubject("中工精品课程修改密码邮件");

    // 创建MimeBodyPart封装正文
    MimeBodyPart text = new MimeBodyPart();

    Date time = new Date();

    String con =
        "尊敬的"
            + user.getNickname()
            + "您好!</br>下面是重置密码的链接,<font color='red'>一个小时之内请点击进入重置密码,否则失效</font>,我会等着你的哦!"
            + "<div><a href='http://localhost:8080/ExcellentCourse/servlet/ResetPwdServlet?uid="
            + user.getId()
            + "&time="
            + time.getTime()
            + "'>重置密码   uid="
            + user.getId()
            + "  time="
            + time.getTime()
            + " </a></div>"
            + "<img src='cid:logo'/>";
    text.setContent(con, "text/html;charset=UTF-8");

    // chuangjian image
    // 创建图片
    MimeMultipart mm = new MimeMultipart();

    BodyPart image1 = createInlineImagePart(context.getRealPath("images/email/beauty.jpg"));
    image1.setHeader("Content-ID", "logo");
    mm.addBodyPart(text);
    mm.addBodyPart(image1);
    mm.setSubType("related");

    message.setContent(mm);
    message.saveChanges();
    // message.writeTo(new FileOutputStream("c:\\1.eml"));
    return message;
  }
 @Override
 protected void sendReminder(CalendarItem calItem, Invite invite) throws Exception {
   Account account = calItem.getAccount();
   Locale locale = account.getLocale();
   TimeZone tz = Util.getAccountTimeZone(account);
   MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSmtpSession(account));
   String to = account.getAttr(Provisioning.A_zimbraCalendarReminderDeviceEmail);
   if (to == null) {
     ZimbraLog.scheduler.info(
         "Unable to send calendar reminder sms since %s is not set",
         Provisioning.A_zimbraCalendarReminderDeviceEmail);
     return;
   }
   mm.setRecipient(javax.mail.Message.RecipientType.TO, new JavaMailInternetAddress(to));
   mm.setText(getText(calItem, invite, locale, tz), MimeConstants.P_CHARSET_UTF8);
   mm.saveChanges();
   MailSender mailSender = calItem.getMailbox().getMailSender();
   mailSender.setSaveToSent(false);
   mailSender.sendMimeMessage(null, calItem.getMailbox(), mm);
 }
Exemple #17
0
  public static void exec(String mailbox, String title, String content) throws Exception {

    String mail_from = MailBean.mailAddress; // mailbox 发送到哪 title 标题
    Properties props = new Properties();

    props.put("mail.smtp.host", MailBean.mailServer);

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

    Session s = Session.getInstance(props);

    s.setDebug(true);

    MimeMessage message = new MimeMessage(s);

    InternetAddress from = new InternetAddress(mail_from);

    message.setFrom(from);

    InternetAddress to = new InternetAddress(mailbox);

    message.setRecipient(Message.RecipientType.TO, to);

    message.setSubject(title);

    message.setText(content);

    message.setContent(content, "text/html;charset=gbk");

    message.setSentDate(new Date());

    message.saveChanges();

    Transport transport = s.getTransport("smtp");

    transport.connect(MailBean.mailServer, MailBean.mailCount, MailBean.mailPassword);

    transport.sendMessage(message, message.getAllRecipients());

    transport.close();
  }
Exemple #18
0
  String sendMail(String sends, String subject, String msg) {
    if (!isSend) return "发送失败,未开启发送功能";
    if (null == msg || "".equals(msg)) return "内容为空";
    if (null == sends || "".equals(sends)) return "收件人为空";

    String result = "";
    try {
      Properties props = new Properties();
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.auth", true);
      Session session = Session.getDefaultInstance(props, null);
      session.setDebug(false);

      MimeMessage mimeMessage = new MimeMessage(session);
      mimeMessage.setFrom(new InternetAddress(fromMail));
      sends = sends.replace(",", ",");
      String[] tomails = StrUtils.split(sends, ',');
      InternetAddress[] internetAddresses = new InternetAddress[tomails.length];
      if (null != tomails && tomails.length > 0) {
        for (int i = 0; i < tomails.length; i++) {
          internetAddresses[i] = new InternetAddress(tomails[i].trim());
        }
      }

      mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses);
      mimeMessage.setSentDate(new Date());
      mimeMessage.setSubject(subject);
      mimeMessage.setContent(msg, "text/html;charset=UTF-8");
      mimeMessage.saveChanges(); // 存储邮件信息

      Transport transport = session.getTransport("smtp");
      transport.connect(host, fromMail, pwd); // 以smtp方式登录邮箱
      transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); // 发送邮件,其中第二个参数是所有
      transport.close();
      result = "邮件发送成功:" + sends;
    } catch (Exception e) {
      e.printStackTrace();
      result = "邮件发送失败:" + sends;
    }
    return result;
  }
    public static void send(String subject, String filePath, final Properties config) {
      Session session =
          Session.getInstance(
              config,
              new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(
                      config.getProperty("mail.userName"), config.getProperty("mail.password"));
                }
              });

      try {
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject(subject, "UTF-8");
        mimeMessage.setFrom(new InternetAddress(config.getProperty("mail.from")));
        mimeMessage.setReplyTo(
            new Address[] {new InternetAddress(config.getProperty("mail.from"))});
        mimeMessage.setRecipients(
            MimeMessage.RecipientType.TO, InternetAddress.parse(config.getProperty("mail.to")));

        MimeMultipart mimeMultipart = new MimeMultipart("mixed");
        MimeBodyPart attch1 = new MimeBodyPart();
        mimeMultipart.addBodyPart(attch1);
        mimeMessage.setContent(mimeMultipart);

        DataSource ds1 = new FileDataSource(filePath);
        DataHandler dataHandler1 = new DataHandler(ds1);
        attch1.setDataHandler(dataHandler1);
        attch1.setFileName(MimeUtility.encodeText(FilenameUtils.getName(filePath)));

        mimeMessage.saveChanges();

        Transport.send(mimeMessage);
      } catch (MessagingException e) {
        throw new RuntimeException("MessagingException", e);
      } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("UnsupportedEncodingException", e);
      }
    }
Exemple #20
0
  private void forwardMail(Session session, String from, String subject, String to, String bodytext)
      throws Exception, MessagingException { // 转发邮件
    session.setDebug(true);

    MimeMessage fordward = new MimeMessage(session);
    fordward.setFrom(new InternetAddress(from));
    fordward.setSubject(subject);
    fordward.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

    Multipart mp = new MimeMultipart();
    MimeBodyPart mbp = new MimeBodyPart();
    // mail.getMailContent((Part)mail.mimeMsg);
    mbp.setContent(
        "<meta http-equiv=Content-Type content=text/html; charset=GBK>" + bodytext,
        "text/html;charset=gb2312");
    mp.addBodyPart(mbp);
    fordward.setContent(mp); // Multipart加入到信件
    fordward.setSentDate(new Date()); // 设置信件头的发送日期
    // 发送信件
    fordward.saveChanges();
    Transport.send(fordward);
  }
Exemple #21
0
  private void replyMail(
      Session session, String smtpHost, String username, String password, String comment)
      throws Exception { // �ظ��ʼ�

    Log.v("YYC", "mimeMsg------>" + mimeMsg);
    MimeMessage msg = (MimeMessage) this.mimeMsg.reply(false);
    msg.setFrom(new InternetAddress(username));
    msg.setRecipients(Message.RecipientType.TO, from);
    Multipart mp = new MimeMultipart();
    MimeBodyPart mbp = new MimeBodyPart();
    mbp.setContent(
        "<meta http-equiv=Content-Type content=text/html; charset=GBK>" + comment,
        "text/html;charset=gb2312");
    mp.addBodyPart(mbp);
    msg.setContent(mp);
    msg.setSentDate(new Date());
    msg.saveChanges();
    Transport trans = session.getTransport("smtp");
    trans.connect(smtpHost, username, password);
    trans.sendMessage(msg, msg.getAllRecipients());
    trans.close();
  }
Exemple #22
0
  private static MimeMessage createMsg(
      String to,
      String from,
      String cc,
      String bcc,
      String message,
      String subject,
      Session session)
      throws Exception {

    if (logger.isTraceEnabled())
      logger.trace(
          String.format(
              "createMsg(to=%s, from=%s, cc=%s, bcc=%s, message=%s, subject=%s)",
              String.valueOf(to),
              String.valueOf(from),
              String.valueOf(cc),
              String.valueOf(bcc),
              String.valueOf(message),
              String.valueOf(subject)));

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(tranFromAddr(from));
    if (to != null && !"".equals(to.trim())) {
      msg.setRecipients(Message.RecipientType.TO, UtilsTools.tranAddr(to.trim()));
    }
    if (cc != null && !"".equals(cc.trim())) {
      msg.setRecipients(Message.RecipientType.CC, UtilsTools.tranAddr(cc.trim()));
    }
    if (bcc != null && !"".equals(bcc.trim())) {
      msg.setRecipients(Message.RecipientType.BCC, UtilsTools.tranAddr(bcc.trim()));
    }
    msg.setSubject(subject);
    msg.setText(message);

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

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

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

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

    Date sendDate = new Date();

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

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

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

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

        MimeMultipart contentMail = new MimeMultipart("related");

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

            MimeBodyPart attachment = new MimeBodyPart();

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

            contentMail.addBodyPart(attachment);
          }
        }

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

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

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

      msg.saveChanges();

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

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

        w.println("FROM:");
        w.println(sender.toString());
        w.print("TO: #");
        w.println(Integer.toString(recipients.size()));
        for (InternetAddress recipient : recipients) {
          w.println(recipient.toString());
        }
        if (ccRecipients != null) {
          w.print("CC: #");
          w.println(Integer.toString(ccRecipients.size()));
          for (InternetAddress ccRecipient : ccRecipients) {
            w.println(ccRecipient.toString());
          }
        }
        if (bccRecipients != null) {
          w.print("BCC: #");
          w.println(Integer.toString(bccRecipients.size()));
          for (InternetAddress bccRecipient : bccRecipients) {
            w.println(bccRecipient.toString());
          }
        }
        w.println("SUBJECT:");
        w.println(subject);
        w.print("IS HTML: ");
        w.println(isHTML);
        w.println("CONTENT:");
        w.print("--BEGIN--");
        w.print(content);
        w.println("--END--");
        w.println("");
        w.flush();
      } catch (IOException e) {
        throw new RuntimeException("Exception when writing debug mail file.", e);
      } finally {
        ResourceHelper.safeClose(out);
      }
    }
    logger.info("Mail sent to: " + recipientsStr);
  }
Exemple #25
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;
  }
  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;
  }
Exemple #27
0
  @SuppressWarnings("deprecation")
  @Override
  public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) {
    HttpRequestBase httpMethod =
        (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String path = PropertyExpander.expandProperties(context, request.getPath());
    StringBuffer query = new StringBuffer();
    String encoding =
        System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding()));

    StringToStringMap responseProperties =
        (StringToStringMap) context.getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

    MimeMultipart formMp =
        "multipart/form-data".equals(request.getMediaType())
                && httpMethod instanceof HttpEntityEnclosingRequestBase
            ? new MimeMultipart()
            : null;

    RestParamsPropertyHolder params = request.getParams();

    for (int c = 0; c < params.getPropertyCount(); c++) {
      RestParamProperty param = params.getPropertyAt(c);

      String value = PropertyExpander.expandProperties(context, param.getValue());
      responseProperties.put(param.getName(), value);

      List<String> valueParts =
          sendEmptyParameters(request) || (!StringUtils.hasContent(value) && param.getRequired())
              ? RestUtils.splitMultipleParametersEmptyIncluded(
                  value, request.getMultiValueDelimiter())
              : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter());

      // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
      // the URI handling further down)
      if (value != null
          && param.getStyle() != ParameterStyle.HEADER
          && param.getStyle() != ParameterStyle.TEMPLATE
          && !param.isDisableUrlEncoding()) {
        try {
          if (StringUtils.hasContent(encoding)) {
            value = URLEncoder.encode(value, encoding);
            for (int i = 0; i < valueParts.size(); i++)
              valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding));
          } else {
            value = URLEncoder.encode(value);
            for (int i = 0; i < valueParts.size(); i++)
              valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
          }
        } catch (UnsupportedEncodingException e1) {
          SoapUI.logError(e1);
          value = URLEncoder.encode(value);
          for (int i = 0; i < valueParts.size(); i++)
            valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
        }
        // URLEncoder replaces space with "+", but we want "%20".
        value = value.replaceAll("\\+", "%20");
        for (int i = 0; i < valueParts.size(); i++)
          valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20"));
      }

      if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) {
        if (!StringUtils.hasContent(value) && !param.getRequired()) continue;
      }

      switch (param.getStyle()) {
        case HEADER:
          for (String valuePart : valueParts) httpMethod.addHeader(param.getName(), valuePart);
          break;
        case QUERY:
          if (formMp == null || !request.isPostQueryString()) {
            for (String valuePart : valueParts) {
              if (query.length() > 0) query.append('&');

              query.append(URLEncoder.encode(param.getName()));
              query.append('=');
              if (StringUtils.hasContent(valuePart)) query.append(valuePart);
            }
          } else {
            try {
              addFormMultipart(
                  request, formMp, param.getName(), responseProperties.get(param.getName()));
            } catch (MessagingException e) {
              SoapUI.logError(e);
            }
          }

          break;
        case TEMPLATE:
          try {
            value =
                getEncodedValue(
                    value,
                    encoding,
                    param.isDisableUrlEncoding(),
                    request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value);
          } catch (UnsupportedEncodingException e) {
            SoapUI.logError(e);
          }
          break;
        case MATRIX:
          try {
            value =
                getEncodedValue(
                    value,
                    encoding,
                    param.isDisableUrlEncoding(),
                    request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
          } catch (UnsupportedEncodingException e) {
            SoapUI.logError(e);
          }

          if (param.getType().equals(XmlBoolean.type.getName())) {
            if (value.toUpperCase().equals("TRUE") || value.equals("1")) {
              path += ";" + param.getName();
            }
          } else {
            path += ";" + param.getName();
            if (StringUtils.hasContent(value)) {
              path += "=" + value;
            }
          }
          break;
        case PLAIN:
          break;
      }
    }

    if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES))
      path = PathUtils.fixForwardSlashesInPath(path);

    if (PathUtils.isHttpPath(path)) {
      try {
        // URI(String) automatically URLencodes the input, so we need to
        // decode it first...
        URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
        context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
        java.net.URI oldUri = httpMethod.getURI();
        httpMethod.setURI(
            HttpUtils.createUri(
                oldUri.getScheme(),
                oldUri.getRawUserInfo(),
                oldUri.getHost(),
                oldUri.getPort(),
                oldUri.getRawPath(),
                uri.getEscapedQuery(),
                oldUri.getRawFragment()));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    } else if (StringUtils.hasContent(path)) {
      try {
        java.net.URI oldUri = httpMethod.getURI();
        String pathToSet =
            StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath())
                ? oldUri.getRawPath() + path
                : path;
        java.net.URI newUri =
            URIUtils.createURI(
                oldUri.getScheme(),
                oldUri.getHost(),
                oldUri.getPort(),
                pathToSet,
                oldUri.getQuery(),
                oldUri.getFragment());
        httpMethod.setURI(newUri);
        context.setProperty(
            BaseHttpRequestTransport.REQUEST_URI,
            new URI(
                newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    }

    if (query.length() > 0 && !request.isPostQueryString()) {
      try {
        java.net.URI oldUri = httpMethod.getURI();
        httpMethod.setURI(
            URIUtils.createURI(
                oldUri.getScheme(),
                oldUri.getHost(),
                oldUri.getPort(),
                oldUri.getRawPath(),
                query.toString(),
                oldUri.getFragment()));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    }

    if (request instanceof RestRequest) {
      String acceptEncoding = ((RestRequest) request).getAccept();
      if (StringUtils.hasContent(acceptEncoding)) {
        httpMethod.setHeader("Accept", acceptEncoding);
      }
    }

    if (formMp != null) {
      // create request message
      try {
        if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
          String requestContent =
              PropertyExpander.expandProperties(
                  context, request.getRequestContent(), request.isEntitizeProperties());
          if (StringUtils.hasContent(requestContent)) {
            initRootPart(request, requestContent, formMp);
          }
        }

        for (Attachment attachment : request.getAttachments()) {
          MimeBodyPart part = new PreencodedMimeBodyPart("binary");

          if (attachment instanceof FileAttachment<?>) {
            String name = attachment.getName();
            if (StringUtils.hasContent(attachment.getContentID())
                && !name.equals(attachment.getContentID())) name = attachment.getContentID();

            part.setDisposition(
                "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"");
          } else part.setDisposition("form-data; name=\"" + attachment.getName() + "\"");

          part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));

          formMp.addBodyPart(part);
        }

        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(formMp);
        message.saveChanges();
        RestRequestMimeMessageRequestEntity mimeMessageRequestEntity =
            new RestRequestMimeMessageRequestEntity(message, request);
        ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
        httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
        httpMethod.setHeader("MIME-Version", "1.0");
      } catch (Throwable e) {
        SoapUI.logError(e);
      }
    } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
      if (StringUtils.hasContent(request.getMediaType()))
        httpMethod.setHeader(
            "Content-Type", getContentTypeHeader(request.getMediaType(), encoding));

      if (request.isPostQueryString()) {
        try {
          ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString()));
        } catch (UnsupportedEncodingException e) {
          SoapUI.logError(e);
        }
      } else {
        String requestContent =
            PropertyExpander.expandProperties(
                context, request.getRequestContent(), request.isEntitizeProperties());
        List<Attachment> attachments = new ArrayList<Attachment>();

        for (Attachment attachment : request.getAttachments()) {
          if (attachment.getContentType().equals(request.getMediaType())) {
            attachments.add(attachment);
          }
        }

        if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) {
          try {
            byte[] content =
                encoding == null ? requestContent.getBytes() : requestContent.getBytes(encoding);
            ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content));
          } catch (UnsupportedEncodingException e) {
            ((HttpEntityEnclosingRequest) httpMethod)
                .setEntity(new ByteArrayEntity(requestContent.getBytes()));
          }
        } else if (attachments.size() > 0) {
          try {
            MimeMultipart mp = null;

            if (StringUtils.hasContent(requestContent)) {
              mp = new MimeMultipart();
              initRootPart(request, requestContent, mp);
            } else if (attachments.size() == 1) {
              ((HttpEntityEnclosingRequest) httpMethod)
                  .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1));

              httpMethod.setHeader(
                  "Content-Type", getContentTypeHeader(request.getMediaType(), encoding));
            }

            if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) {
              if (mp == null) mp = new MimeMultipart();

              // init mimeparts
              AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap());

              // create request message
              MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
              message.setContent(mp);
              message.saveChanges();
              RestRequestMimeMessageRequestEntity mimeMessageRequestEntity =
                  new RestRequestMimeMessageRequestEntity(message, request);
              ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
              httpMethod.setHeader(
                  "Content-Type",
                  getContentTypeHeader(
                      mimeMessageRequestEntity.getContentType().getValue(), encoding));
              httpMethod.setHeader("MIME-Version", "1.0");
            }
          } catch (Exception e) {
            SoapUI.logError(e);
          }
        }
      }
    }
  }
  protected void sendPasswordResetEMail(
      HttpServletRequest request, ICFSecuritySecUserObj resetUser, ICFSecurityClusterObj cluster)
      throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk26SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk26SmtpEmailFrom");
    }

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk26SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk26SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk26SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk26SmtpPassword");
    }

    Session emailSess =
        Session.getInstance(
            props,
            new Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
              }
            });

    String thisURI =
        request.getScheme()
            + "://"
            + request.getServerName()
            + ":"
            + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody =
        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n"
            + "<HTML>\n"
            + "<BODY>\n"
            + "<p>\n"
            + "You requested a password reset for "
            + resetUser.getRequiredEMailAddress()
            + " used for accessing "
            + clusterDescription
            + ".\n"
            + "<p>"
            + "Please click on the following link to reset your password:<br>\n"
            + "<A HRef=\""
            + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "\">"
            + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "</A>\n"
            + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n"
            + "<A HRef=\""
            + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "\">"
            + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "</A>\n"
            + "</BODY>\n"
            + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject(
        "You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
  }
Exemple #29
0
  public static boolean sendMail(
      String userName,
      String passWord,
      String host,
      String port,
      String starttls,
      String auth,
      boolean debug,
      String socketFactoryClass,
      String fallback,
      String[] to,
      String[] cc,
      String[] bcc,
      String subject,
      String text,
      String attachmentPath,
      String attachmentName) {

    // Object Instantiation of a properties file.
    Properties props = new Properties();

    props.put("mail.smtp.user", userName);

    props.put("mail.smtp.host", host);

    if (!"".equals(port)) {
      props.put("mail.smtp.port", port);
    }

    if (!"".equals(starttls)) {
      props.put("mail.smtp.starttls.enable", starttls);
      props.put("mail.smtp.auth", auth);
    }

    if (debug) {

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

    } else {

      props.put("mail.smtp.debug", "false");
    }

    if (!"".equals(port)) {
      props.put("mail.smtp.socketFactory.port", port);
    }
    if (!"".equals(socketFactoryClass)) {
      props.put("mail.smtp.socketFactory.class", socketFactoryClass);
    }
    if (!"".equals(fallback)) {
      props.put("mail.smtp.socketFactory.fallback", fallback);
    }

    try {

      Session session = Session.getDefaultInstance(props, null);

      session.setDebug(debug);

      MimeMessage msg = new MimeMessage(session);

      msg.setText(text);

      msg.setSubject(subject);

      Multipart multipart = new MimeMultipart();
      MimeBodyPart messageBodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource(attachmentPath);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(attachmentName);
      multipart.addBodyPart(messageBodyPart);

      msg.setContent(multipart);
      msg.setFrom(new InternetAddress(userName));

      for (int i = 0; i < to.length; i++) {
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
      }

      for (int i = 0; i < cc.length; i++) {
        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
      }

      for (int i = 0; i < bcc.length; i++) {
        msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
      }

      msg.saveChanges();

      Transport transport = session.getTransport("smtp");

      transport.connect(host, userName, passWord);

      transport.sendMessage(msg, msg.getAllRecipients());

      transport.close();

      return true;

    } catch (Exception mex) {
      mex.printStackTrace();
      return false;
    }
  }
  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");
  }