コード例 #1
0
  protected void fillContent(Message email, Execution execution, JCRSessionWrapper session)
      throws MessagingException {
    String text = getTemplate().getText();
    String html = getTemplate().getHtml();
    List<AttachmentTemplate> attachmentTemplates = getTemplate().getAttachmentTemplates();

    try {
      if (html != null || !attachmentTemplates.isEmpty()) {
        // multipart
        MimeMultipart multipart = new MimeMultipart("related");

        BodyPart p = new MimeBodyPart();
        Multipart alternatives = new MimeMultipart("alternative");
        p.setContent(alternatives, "multipart/alternative");
        multipart.addBodyPart(p);

        // html
        if (html != null) {
          BodyPart htmlPart = new MimeBodyPart();
          html = evaluateExpression(execution, html, session);
          htmlPart.setContent(html, "text/html; charset=UTF-8");
          alternatives.addBodyPart(htmlPart);
        }

        // text
        if (text != null) {
          BodyPart textPart = new MimeBodyPart();
          text = evaluateExpression(execution, text, session);
          textPart.setContent(text, "text/plain; charset=UTF-8");
          alternatives.addBodyPart(textPart);
        }

        // attachments
        if (!attachmentTemplates.isEmpty()) {
          addAttachments(execution, multipart);
        }

        email.setContent(multipart);
      } else if (text != null) {
        // unipart
        text = evaluateExpression(execution, text, session);
        email.setText(text);
      }
    } catch (RepositoryException e) {
      logger.error(e.getMessage(), e);
    } catch (ScriptException e) {
      logger.error(e.getMessage(), e);
    }
  }
コード例 #2
0
  Multipart composeMessageBody(ItemOrder order) throws MessagingException {
    String html = htmlCreator.generateHtmlImage(order.getItemResponse().getImgBaseSrc());

    BodyPart mediaPart = new MimeBodyPart();
    mediaPart.setContent(html, "text/html");

    BodyPart textPart = new MimeBodyPart();
    textPart.setContent(order.dump(), "text/plain; charset=UTF-8");

    Multipart messageBody = new MimeMultipart();
    messageBody.addBodyPart(textPart);
    messageBody.addBodyPart(mediaPart);

    return messageBody;
  }
コード例 #3
0
  @Override
  public void sendAsHtml(
      String subject, String html, Collection<String> recipients, Map<String, Object> htmlParams)
      throws Exception {
    Address[] addresses = new Address[recipients.size()];
    Iterator<String> iterator = recipients.iterator();
    int i = 0;
    while (iterator.hasNext()) {
      addresses[i] = new InternetAddress(iterator.next());
      i++;
    }

    Template template = configuration.getTemplate(html);
    Writer writer = new StringWriter();
    template.process(htmlParams, writer);

    BodyPart bodyPart = new MimeBodyPart();
    bodyPart.setContent(writer.toString(), "text/html");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(bodyPart);

    Message message = new MimeMessage(session);
    message.setFrom();
    message.setRecipients(Message.RecipientType.TO, addresses);
    message.setSubject(subject);
    message.setContent(multipart, "text/html");

    Transport.send(message);
  }
コード例 #4
0
  /** * 处理附件型邮件时,需要为邮件体和附件体分别创建BodyPort对象 然后将其置入MimeMultipart对象中作为一个整体进行发送 */
  @Override
  protected void setContent(MimeMessage message) throws MailException {
    try {
      Multipart multipart = new MimeMultipart();
      // 文本
      BodyPart textBodyPart = new MimeBodyPart();
      multipart.addBodyPart(textBodyPart);
      textBodyPart.setContent(text, "text/html;charset=" + charset);

      // 附件
      for (File attachment : attachments) {
        BodyPart fileBodyPart = new MimeBodyPart();
        multipart.addBodyPart(fileBodyPart);
        FileDataSource fds = new FileDataSource(attachment);
        fileBodyPart.setDataHandler(new DataHandler(fds));
        // 中文乱码
        String attachmentName = fds.getName();
        fileBodyPart.setFileName(MimeUtility.encodeText(attachmentName));
      }
      // 内容
      message.setContent(multipart);
    } catch (Exception e) {
      new MailException(e.getMessage());
    }
  }
コード例 #5
0
ファイル: Memo.java プロジェクト: flabser/NB3
  private void _Memo(
      String sender, String personal, List<String> recipients, String subj, String body) {
    if (Environment.mailEnable) {
      Properties props = new Properties();
      props.put("mail.smtp.host", smtpServer);
      Session ses;
      if (smtpAuth) {
        props.put("mail.smtp.auth", smtpAuth);
        props.put("mail.smtp.port", smtpPort);
        if ("465".equals(smtpPort)) {
          props.put("mail.smtp.ssl.enable", "true");
        }
        Authenticator auth = new SMTPAuthenticator();
        ses = Session.getInstance(props, auth);
      } else {
        ses = Session.getInstance(props, null);
      }

      msg = new MimeMessage(ses);
      hasRecipients = false;

      try {
        if (personal == null) {
          msg.setFrom(new InternetAddress(sender));
        } else {
          msg.setFrom(new InternetAddress(sender, personal));
        }

        for (String recipient : recipients) {
          try {
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            hasRecipients = true;
          } catch (AddressException ae) {
            Server.logger.errorLogEntry("incorrect e-mail \"" + recipient + "\"");
            continue;
          }
        }

        if (hasRecipients) {
          msg.setSubject(subj, "utf-8");
          Multipart mp = new MimeMultipart();
          BodyPart htmlPart = new MimeBodyPart();
          htmlPart.setContent(body, "text/html; charset=utf-8");
          mp.addBodyPart(htmlPart);
          msg.setContent(mp);
          isValid = true;
        } else {
          Server.logger.errorLogEntry(
              "unable to send the message. List of recipients is empty or consist is incorrect data");
        }
      } catch (MessagingException e) {
        Server.logger.errorLogEntry(e);
      } catch (UnsupportedEncodingException e) {
        Server.logger.errorLogEntry(e);
      }
    }
  }
コード例 #6
0
  /*
   * Writes/Sends an Email
   */
  public void writeConfirmationEmail(
      String firstName, String lastName, String username, String password, String email) {
    String to = email;
    String from = "*****@*****.**";
    String host = "smtp.ilstu.edu";
    Properties properties = System.getProperties();

    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.user", "cssumne"); // if needed
    properties.setProperty("mail.password", "stuC0rb!"); // if needed
    Session session = Session.getDefaultInstance(properties);

    try {
      MimeMessage message = new MimeMessage(session);
      MimeMultipart multipart = new MimeMultipart("related");
      BodyPart messageBodyPart = new MimeBodyPart();
      message.setFrom(new InternetAddress(from));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject("Profile Created!");

      String htmlText =
          "<h1>Congratulations, "
              + firstName
              + " "
              + lastName
              + "! Your Profile has been created!</h1>"
              + "<img src=\"cid:image\">"
              + "<p>Username: "******"</p>"
              + "<p>Email: "
              + email
              + "</p>"
              + "<p>Password: "******"</p>"
              + "<p>Thank You for Joining!</p>";

      messageBodyPart.setContent(htmlText, "text/html");
      multipart.addBodyPart(messageBodyPart);
      messageBodyPart = new MimeBodyPart();
      DataSource fds;
      fds =
          new FileDataSource(
              "C:\\Users\\Corbin\\Desktop\\Github\\WebDevSemesterProject\\SilentAuction\\web\\resources\\bf_logo.png");
      messageBodyPart.setDataHandler(new DataHandler(fds));
      messageBodyPart.setHeader("Content-ID", "<image>");
      multipart.addBodyPart(messageBodyPart);
      message.setContent(multipart);

      Transport.send(message);

      System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
  }
コード例 #7
0
    public void send(final Email email) throws MessagingException {
      if (email.getMessage().getSender().getFromName() == null) {
        logProblem("error.from.address.cannot.be.null");
        abort();
        return;
      }

      final String from =
          constructFromString(
              encode(email.getMessage().getFromName()), email.getMessage().getFromAddress());

      final String[] replyTos = email.replyTos();
      final Address[] replyToAddresses = new Address[replyTos == null ? 0 : replyTos.length];
      if (replyTos != null) {
        for (int i = 0; i < replyTos.length; i++) {
          try {
            replyToAddresses[i] = new InternetAddress(encode(replyTos[i]));
          } catch (final AddressException e) {
            logProblem("invalid.reply.to.address: " + replyTos[i]);
            abort();
            return;
          }
        }
      }

      setFrom(new InternetAddress(from));
      setSubject(encode(email.getSubject()));
      setReplyTo(replyToAddresses);

      final String body = email.getBody();
      final String htmlBody = getHtmlBody();

      final MimeMultipart mimeMultipart = createMimeMultipart(body, htmlBody);

      if (body != null && !body.trim().isEmpty()) {
        final BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(body);
        mimeMultipart.addBodyPart(bodyPart);
      }

      if (htmlBody != null && !htmlBody.trim().isEmpty()) {
        final BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent(htmlBody, "text/html; charset=utf-8");
        mimeMultipart.addBodyPart(bodyPart);
      }

      setContent(mimeMultipart);

      addRecipientsAux();

      LOG.info("Sending email {} with message id {}", email.getExternalId(), getMessageID());

      Transport.send(this);

      final Address[] allRecipients = getAllRecipients();
      setConfirmedAddresses(allRecipients);
    }
コード例 #8
0
ファイル: MailBuilder.java プロジェクト: AlexCAB/CLIMailer
 /**
  * Build mail for sending.
  *
  * @param record - recipients data line (from '-d')
  * @return - built email.
  * @throws Exception
  */
 public MimeMultipart buildMailForSand(CSVRecord record) throws Exception {
   MimeMultipart multipart = new MimeMultipart();
   // Build and add message
   BodyPart messageBodyPart = new MimeBodyPart();
   messageBodyPart.setContent(buildEmailBody(record), "text/html; charset=utf-8");
   multipart.addBodyPart(messageBodyPart);
   // Add attachment
   for (MimeBodyPart attachment : attachmentsList) {
     multipart.addBodyPart(attachment);
   }
   return multipart;
 }
コード例 #9
0
ファイル: Mail.java プロジェクト: httplife/wd_proxy_monitor
  /**
   * 设置邮件正文
   *
   * @param mailBody String
   */
  public boolean setBody(String mailBody) {
    try {
      BodyPart bp = new MimeBodyPart();
      bp.setContent("" + mailBody, "text/html;charset=GBK");
      mp.addBodyPart(bp);

      return true;
    } catch (Exception e) {
      System.err.println("设置邮件正文时发生错误!" + e);
      return false;
    }
  }
コード例 #10
0
ファイル: Mailer.java プロジェクト: GunioRobot/ping-service
  public void sendMail2(
      String mimeType,
      String from,
      String to,
      String subject,
      String text,
      MimeBodyPart... attachments) {
    if (Utils.isNullOrEmpty(to)) {
      logger.warn("mail can't be delivered to (recipient == null):\n{}", text);
      return;
    }

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

    Message message = new MimeMessage(session);

    try {
      Multipart mp = new MimeMultipart("mixed");

      BodyPart content = new MimeBodyPart();
      content.setContent(text, mimeType);
      mp.addBodyPart(content);

      if (attachments != null && attachments.length > 0) {
        for (MimeBodyPart attachment : attachments) {
          mp.addBodyPart(attachment);
        }
      }

      message.setFrom(
          new InternetAddress(
              from, from.equals(PING_SERVICE_NOTIFY_GMAIL_COM) ? "Ping Service Notifier" : null));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject(subject);
      message.setContent(mp);
      message.saveChanges();

      Transport.send(message);
    } catch (Exception e) {
      logger.error(
          "Error sending mail:"
              + "\n\tFrom: "
              + from
              + "\n\tTo: "
              + to
              + "\n\tSubject: "
              + subject
              + "\n\tMessage:\n\n"
              + (Utils.isNullOrEmpty(text) ? "-" : text.substring(0, 100) + "..."),
          e);
    }
  }
コード例 #11
0
ファイル: MailSender.java プロジェクト: rockzeng/essh_v1.0
 /**
  * 以HTML格式发送邮件
  *
  * @param entity 待发送的邮件信息
  */
 public boolean sendHtmlMail(MailSenderModel entity) {
   // 判断是否需要身份认证
   MyAuthenticator authenticator = null;
   // 如果需要身份认证,则创建一个密码验证器
   if (entity.isValidate()) {
     authenticator = new MyAuthenticator(entity.getUserName(), entity.getPassword());
   }
   // 根据邮件会话属性和密码验证器构造一个发送邮件的session
   Session sendMailSession = Session.getDefaultInstance(entity.getProperties(), authenticator);
   try {
     // 根据session创建一个邮件消息
     Message mailMessage = new MimeMessage(sendMailSession);
     // 创建邮件发送者地址
     Address from = new InternetAddress(entity.getFromAddress());
     // 设置邮件消息的发送者
     mailMessage.setFrom(from);
     // 创建邮件的接收者地址,并设置到邮件消息中
     // Address to = new InternetAddress();
     // Message.RecipientType.TO属性表示接收者的类型为TO
     mailMessage.setRecipients(
         Message.RecipientType.TO, InternetAddress.parse(entity.getToAddress()));
     // 抄送
     if (entity.getCcAddress() != null && !"".equals(entity.getCcAddress())) {
       mailMessage.setRecipients(
           Message.RecipientType.CC, InternetAddress.parse(entity.getCcAddress()));
     }
     // 暗送
     if (entity.getBccAddress() != null && !"".equals(entity.getBccAddress())) {
       mailMessage.setRecipients(
           Message.RecipientType.BCC, InternetAddress.parse(entity.getBccAddress()));
     }
     // 设置邮件消息的主题
     mailMessage.setSubject(entity.getSubject());
     // 设置邮件消息发送的时间
     mailMessage.setSentDate(new Date());
     // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
     Multipart mainPart = new MimeMultipart();
     // 创建一个包含HTML内容的MimeBodyPart
     BodyPart html = new MimeBodyPart();
     // 设置HTML内容
     html.setContent(entity.getContent(), "text/html; charset=" + DEFAULT_ENCODING);
     mainPart.addBodyPart(html);
     // 将MiniMultipart对象设置为邮件内容
     mailMessage.setContent(mainPart);
     // 发送邮件
     Transport.send(mailMessage);
     return true;
   } catch (MessagingException ex) {
     ex.printStackTrace();
   }
   return false;
 }
コード例 #12
0
ファイル: NoteResource.java プロジェクト: KMax/Quicker-Server
  /**
   * Get a media content by note id and media name
   *
   * @param user user name
   * @param id note id
   * @param blobName name of media
   * @return
   */
  @Path("/{id}/media/{blobName}")
  @GET
  // @Produces("image/jpeg")
  public Response getBLOB(
      @PathParam("user") String user,
      @PathParam("id") int id,
      @PathParam("blobName") String blobName) {
    Response r = null;
    if (userAuth.Auth(hh, user)) {
      Multipart mp = new MimeMultipart();
      BodyPart bp = new MimeBodyPart();
      try {
        bp.setContent(ndb.getBLOBInfo(user, id, blobName), "application/xml");
        mp.addBodyPart(bp);
      } catch (MessagingException ex) {
        ex.printStackTrace();
      }

      ByteArrayInputStream tmp = null;
      try {
        tmp = ndb.getBLOBStream(user, id, blobName);
        BodyPart stream = new MimeBodyPart();
        stream.setContent(tmp, ndb.getBLOBType(user, id, blobName));
        r = Response.ok(mp).build();
      } catch (MessagingException me) {
        me.printStackTrace();
      } finally {
        try {
          tmp.close();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
      }
    } else {
      r = unAuthorized();
    }
    return r;
  }
コード例 #13
0
  public void prepare(MimeMessage message) throws Exception {

    // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369
    if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) {
      message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");
    }

    if (getFrom() != null) {
      List<InternetAddress> toAddress = new ArrayList<InternetAddress>();
      toAddress.add(new InternetAddress(getFrom(), getFromName()));
      message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()]));
    }
    if (getTo() != null) {
      message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo()));
    }
    if (getCc() != null) {
      message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc()));
    }
    if (getSubject() != null) {
      message.setSubject(getSubject());
    }

    MimeMultipart mimeMultipart =
        new MimeMultipart("alternative"); // multipart/mixed or mixed or related or alternative
    message.setContent(mimeMultipart);

    if (getPlainTextContent() != null) {
      BodyPart textBodyPart = new MimeBodyPart();
      textBodyPart.setContent(getPlainTextContent(), "text/plain");
      mimeMultipart.addBodyPart(textBodyPart);
    }

    if (getHtmlContent() != null) {
      BodyPart htmlBodyPart = new MimeBodyPart();
      htmlBodyPart.setContent(getHtmlContent(), "text/html");
      mimeMultipart.addBodyPart(htmlBodyPart);
    }
  }
コード例 #14
0
ファイル: GMail.java プロジェクト: iriand/gmail
  public void send(
      String from,
      String[] recipientsTo,
      String[] recipientsCC,
      String[] recipientsBCC,
      String subject,
      String body,
      String[] files) {

    try {
      Properties properties = System.getProperties();
      setMailServerProperties(username, password, host, properties);

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

      MimeMessage message = new MimeMessage(session);

      message.setFrom(new InternetAddress(from));
      setAllRecipients(recipientsTo, recipientsCC, recipientsBCC, message);
      message.setSubject(subject);

      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setContent(body, "text/html");

      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);

      setAttachments(files, multipart);

      message.setContent(multipart);

      Transport.send(message);
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
コード例 #15
0
  public boolean sendMail() {
    prepare();
    try {
      MimeMessage mimeMessage = new MimeMessage(session);
      mimeMessage.setFrom(new InternetAddress(from));
      InternetAddress address = new InternetAddress(taxPayer.getEmail());
      mimeMessage.addRecipient(RecipientType.TO, address);

      mimeMessage.setSubject("Татварын ерөнхий газар өр дуудах төв ");
      mimeMessage.setText(message());

      MimeMultipart multipart = new MimeMultipart("related");

      BodyPart messageBodyPart = new MimeBodyPart();
      String htmlText = "<H1>МТА ӨР ДУУДАХ ТӨВ</H1><img src=\"cid:image\">";
      htmlText += "<br>" + message();
      messageBodyPart.setContent(htmlText, "text/html;charset=UTF-8");

      multipart.addBodyPart(messageBodyPart);
      /*
      			messageBodyPart = new MimeBodyPart();
      			DataSource fds = new FileDataSource(
      					"C:/Users/Suld/Pictures/image.jpg");

      			messageBodyPart.setDataHandler(new DataHandler(fds));
      			messageBodyPart.setHeader("Content-ID", "<image>");
      */
      multipart.addBodyPart(messageBodyPart);

      mimeMessage.setContent(multipart);

      Transport transport = session.getTransport("smtp");
      transport.connect(host, from, password);
      transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
      transport.close();
      return true;
    } catch (AddressException e) {
      e.printStackTrace();
    } catch (MessagingException e) {
      e.printStackTrace();
    }
    return false;
  }
コード例 #16
0
 @Override
 public Mail send(Mail mail, MailContext ctx) {
   try {
     Session session = ctx.getSession();
     Message mailMessage = new MimeMessage(session);
     // 设置发件人地址
     Address from = new InternetAddress(ctx.getUser() + " <" + ctx.getAccount() + ">");
     mailMessage.setFrom(from);
     // 设置所有收件人的地址
     Address[] to = getAddress(mail.getReceivers());
     mailMessage.setRecipients(Message.RecipientType.TO, to);
     // 设置抄送人地址
     Address[] cc = getAddress(mail.getCcs());
     mailMessage.setRecipients(Message.RecipientType.CC, cc);
     // 设置主题
     mailMessage.setSubject(mail.getSubject());
     // 发送日期
     mailMessage.setSentDate(new Date());
     // 构建整封邮件的容器
     Multipart main = new MimeMultipart();
     // 正文的body
     BodyPart body = new MimeBodyPart();
     body.setContent(mail.getContent(), "text/html; charset=utf-8");
     main.addBodyPart(body);
     // 处理附件
     for (FileObject f : mail.getFiles()) {
       // 每个附件的body
       MimeBodyPart fileBody = new MimeBodyPart();
       fileBody.attachFile(f.getFile());
       // 为文件名进行转码
       fileBody.setFileName(MimeUtility.encodeText(f.getSourceName()));
       main.addBodyPart(fileBody);
     }
     // 将正文的Multipart对象设入Message中
     mailMessage.setContent(main);
     Transport.send(mailMessage);
     return mail;
   } catch (Exception e) {
     e.printStackTrace();
     throw new SendMailException("发送邮件错误, 请检查邮箱配置及邮件的相关信息");
   }
 }
コード例 #17
0
 /**
  * 以HTML格式发送邮件
  *
  * @param mailInfo 待发送的邮件信息
  */
 public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
   // 判断是否需要身份认证
   MyAuthenticator authenticator = null;
   Properties pro = mailInfo.getProperties();
   // 如果需要身份认证,则创建一个密码验证器
   if (mailInfo.isValidate()) {
     authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
   }
   // 根据邮件会话属性和密码验证器构造一个发送邮件的session
   Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
   try {
     // 根据session创建一个邮件消息
     Message mailMessage = new MimeMessage(sendMailSession);
     // 创建邮件发送者地址
     Address from = new InternetAddress(mailInfo.getFromAddress());
     // 设置邮件消息的发送者
     mailMessage.setFrom(from);
     // 创建邮件的接收者地址,并设置到邮件消息中
     Address to = new InternetAddress(mailInfo.getToAddress());
     // Message.RecipientType.TO属性表示接收者的类型为TO
     mailMessage.setRecipient(Message.RecipientType.TO, to);
     // 设置邮件消息的主题
     mailMessage.setSubject(mailInfo.getSubject());
     // 设置邮件消息发送的时间
     mailMessage.setSentDate(new Date());
     // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
     Multipart mainPart = new MimeMultipart();
     // 创建一个包含HTML内容的MimeBodyPart
     BodyPart html = new MimeBodyPart();
     // 设置HTML内容
     html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
     mainPart.addBodyPart(html);
     // 将MiniMultipart对象设置为邮件内容
     mailMessage.setContent(mainPart);
     // 发送邮件
     Transport.send(mailMessage);
     return true;
   } catch (MessagingException ex) {
     ex.printStackTrace();
   }
   return false;
 }
コード例 #18
0
ファイル: SendMail.java プロジェクト: orgranktest/webapp
  public static int sendMail(String toAddr, String ccAddr, String mailTitle, String mailConcept) {
    Session s = Session.getInstance(SendMail.props, null);
    s.setDebug(false);

    Message message = new MimeMessage(s);
    try {
      Address from = new InternetAddress(SendMail.SenderEmailAddr);
      message.setFrom(from);
      Address to = new InternetAddress(toAddr);
      message.setRecipient(Message.RecipientType.TO, to);
      if (ccAddr != null && ccAddr != "") {
        Address cc = new InternetAddress(ccAddr);
        message.setRecipient(Message.RecipientType.CC, cc);
      }

      message.setSubject(mailTitle);
      Multipart mainPart = new MimeMultipart();
      BodyPart html = new MimeBodyPart();
      html.setContent(mailConcept, "text/html;charset=ISO-8859-1");
      mainPart.addBodyPart(html);
      message.setContent(mainPart);
      message.setSentDate(new Date());
      message.saveChanges();

      Transport transport = s.getTransport(SendMail.TransprotType);
      transport.connect(SendMail.SMTPServerName, SendMail.SMTPUserName, SendMail.SMTPPassword);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();

      //			System.out.println("发送邮件,邮件地址:"+toAddr);
      //			System.out.println("发送邮件,邮件地址:"+ccAddr);
      //			System.out.println("标题:"+mailTitle);
      //			System.out.println("内容:"+mailConcept);
      System.out.println("Email Send Success!");
      return 1;
    } catch (Exception e) {
      System.out.println(e.getMessage());
      return -1;
    }
  }
コード例 #19
0
  public static void sendResetLink(String email) {

    String query = "select * from user where email=?";
    String uname = null;
    try {

      PreparedStatement ps = con.prepareStatement(query);
      ps.setString(1, email);
      ResultSet rs = ps.executeQuery();
      rs.next();
      to = email;
      uname = rs.getString("fname") + " " + rs.getString("lname");
      String data = "";
      data +=
          "Dear "
              + uname
              + ", <br/> Here is the link to reset your forgotten password : <br/><br/><a href='http://localhost:8080/OnlineTest/servlet/CreateSession?id="
              + AESCrypto.encrypt(rs.getString("userid"))
              + "' >Click here to reset your password</a><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>";

      Properties properties = System.getProperties();
      properties.put("mail.smtp.starttls.enable", "true");
      properties.put("mail.smtp.host", "smtp.gmail.com");

      properties.put("mail.smtp.port", "587");
      properties.put("mail.smtp.auth", "true");
      Session session =
          Session.getInstance(
              properties,
              new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(
                      "*****@*****.**", "ratindia"); // Specify
                  // the
                  // Username
                  // and
                  // the
                  // PassWord
                }
              });

      try {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject("Password Reset");

        MimeMultipart multipart = new MimeMultipart("related");

        BodyPart messageBodyPart = new MimeBodyPart();
        String htmltext =
            "<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml'><head><title>...::: RAT Online Academic Panel :::...</title></head><body><table style='background:url(cid:bg) no-repeat;'><tr><td><div id='top'  style='margin-top:-60px;height:100px;font-family: Lucida Calligraphy; background-color: #336699; color:cyan;'><img src='cid:logo' height='100' style='float:left'><h1 align='right'>Road Ahead Technologies&nbsp;</h1><h2 align='right'>Online Academic Panel&nbsp;&nbsp;</h2></div><br /><div id='info' style='font-family: Consolas;color:black;font-size:18px;height:400px;'>"
                + data
                + "<table align=center width=700px style='font-size:20px;'><tr><td><a href='http://*****:*****@ RAT 2014 <br/><br />Developed By <a href='http://www.facebook.com/ggauravag'>Gaurav Agarwal</a></div></td></tr></table></body></html>";
        messageBodyPart.setContent(htmltext, "text/html");
        multipart.addBodyPart(messageBodyPart);

        String workingDir = System.getProperty("user.dir");

        String path1 = workingDir.substring(0, (workingDir.length() - 3));
        path1 += "webapps\\OnlineTest\\images\\rat.png";

        DataSource fds = new FileDataSource(path1);
        // DataSource fds = new FileDataSource("rat.png");

        // System.out.println("Current working directory : " +
        // workingDir);

        String path2 = workingDir.substring(0, (workingDir.length() - 3));
        path2 += "webapps\\OnlineTest\\images\\bg.jpg";

        DataSource fds3 = new FileDataSource(path2);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(fds));
        messageBodyPart.addHeader("Content-ID", "<logo>");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(fds3));
        messageBodyPart.addHeader("Content-ID", "<bg>");
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        new Thread(
                new Runnable() {
                  @Override
                  public void run() {
                    try {
                      Transport.send(message);
                    } catch (Exception e) {
                      e.printStackTrace();
                    }
                  }
                })
            .start();

        System.out.println("Sent password reset successfully from admin....");
        session = null;

      } catch (MessagingException mex) {
        mex.printStackTrace();
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #20
0
ファイル: MailSender.java プロジェクト: rockzeng/essh_v1.0
  /**
   * 发送带附件的(HTML)邮件
   *
   * @param entity 待发送的邮件信息
   */
  public boolean sendAffixMail(MailSenderModel entity) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    // 如果需要身份认证,则创建一个密码验证器
    if (entity.isValidate()) {
      authenticator = new MyAuthenticator(entity.getUserName(), entity.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(entity.getProperties(), authenticator);
    try {
      // 根据session创建一个邮件消息
      Message mailMessage = new MimeMessage(sendMailSession);
      // 创建邮件发送者地址
      Address from = new InternetAddress(entity.getFromAddress());
      // 设置邮件消息的发送者
      mailMessage.setFrom(from);
      // 创建邮件的接收者地址,并设置到邮件消息中
      // Address to = new InternetAddress(entity.getToAddress());
      // Message.RecipientType.TO属性表示接收者的类型为TO
      mailMessage.setRecipients(
          Message.RecipientType.TO, InternetAddress.parse(entity.getToAddress()));
      // 抄送
      if (entity.getCcAddress() != null && !"".equals(entity.getCcAddress())) {
        mailMessage.setRecipients(
            Message.RecipientType.CC, InternetAddress.parse(entity.getCcAddress()));
      }

      // 暗送
      if (entity.getBccAddress() != null && !"".equals(entity.getBccAddress())) {
        mailMessage.setRecipients(
            Message.RecipientType.BCC, InternetAddress.parse(entity.getBccAddress()));
      }
      // 设置邮件消息的主题
      mailMessage.setSubject(entity.getSubject());
      // 设置邮件消息发送的时间
      mailMessage.setSentDate(new Date());
      // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
      Multipart mainPart = new MimeMultipart();
      // 创建一个包含HTML内容的MimeBodyPart
      BodyPart html = new MimeBodyPart();
      // 设置HTML内容
      html.setContent(entity.getContent(), "text/html; charset=" + DEFAULT_ENCODING);
      mainPart.addBodyPart(html);

      // 组装附件
      MimeBodyPart file;
      String[] filePaths = entity.getAttachFileNames();
      FileDataSource file_datasource = null;
      if (filePaths != null && filePaths.length > 0) {
        for (int i = 0; i < filePaths.length; i++) {
          file = new MimeBodyPart();
          file_datasource = new FileDataSource(new File(filePaths[i]));
          DataHandler dh = new DataHandler(file_datasource);
          file.setDataHandler(dh);
          // 附件区别内嵌内容的一个特点是有文件名,为防止中文乱码要编码
          file.setFileName(MimeUtility.encodeText(dh.getName(), DEFAULT_ENCODING, null));
          System.out.println(dh.getName());
          mainPart.addBodyPart(file);
        }
      }

      // 将MiniMultipart对象设置为邮件内容
      mailMessage.setContent(mainPart);

      // 发送邮件
      Transport.send(mailMessage);
      return true;
    } catch (MessagingException ex) {
      ex.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
コード例 #21
0
ファイル: SendMail.java プロジェクト: pttien/tieuluan1310
  public static void sendMail(String mail, MailContent mailContent) throws Exception {

    Properties props = new Properties();
    //		try {
    //			props.load(new FileInputStream(new File("settings.properties")));
    //		} catch (FileNotFoundException e1) {
    //			e1.printStackTrace();
    //		} catch (IOException e1) {
    //			e1.printStackTrace();
    //		}

    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {

              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("*****@*****.**", "mycity@123");
              }
            });

    try {
      String a = mail;
      String b = mailContent.getTopp();
      String c = mailContent.getBody1();
      String d = mailContent.getBody2();
      Message message = new MimeMessage(session);
      //			MimeUtility.encodeText(subject, "utf-8", "B")
      message.setFrom(new InternetAddress("*****@*****.**"));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail));
      message.setSubject(MimeUtility.encodeText(mailContent.getSubJect(), "utf-8", "B"));

      BodyPart body = new MimeBodyPart();
      // freemarker stuff.
      Configuration cfg = new Configuration();
      FileTemplateLoader ftl1 =
          new FileTemplateLoader(
              new File(ServletActionContext.getServletContext().getRealPath("/")));
      cfg.setClassForTemplateLoading(cfg.getClass(), "/");
      cfg.setTemplateLoader(ftl1);
      Template template = null;
      template =
          cfg.getTemplate("resources/mycity_cms/templates/mail/html-mail-template.html", "UTF-8");

      Map<String, String> rootMap = new HashMap<String, String>();
      rootMap.put("to", mailContent.getTopp());
      rootMap.put("body1", mailContent.getBody1());
      rootMap.put("body2", mailContent.getBody2());
      Writer out = new StringWriter();
      template.process(rootMap, out);
      // freemarker stuff ends.

      /* you can add html tags in your text to decorate it. */
      //			body.setContent(out.toString(),	"text/html");
      body.setContent(out.toString(), "text/html; charset=UTF-8");

      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(body);
      // cfg
      //			body = new MimeBodyPart();
      //
      //			String filename = "hello.txt";
      //			DataSource source = new FileDataSource(filename);
      //			body.setDataHandler(new DataHandler(source));
      //			body.setFileName(filename);
      //			multipart.addBodyPart(body);
      //
      message.setContent(multipart, "text/html; charset=UTF-8;");
      //
      Transport.send(message);

    } catch (MessagingException e) {
      LogUtility.logError(e, e.getMessage());
    }

    System.out.println("Done....");
  }
コード例 #22
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;
  }
コード例 #23
0
  /**
   * Creates a mime-message, multipart if attachements are supplied otherwise as plain text. Assumes
   * UTF-8 encoding for both subject and content.
   *
   * @param session, must be specified
   * @param from, can be null
   * @param to, can be null or empty
   * @param subject, can be null
   * @param content, must be specified
   * @param attachments, can be null or empty
   * @return the mime-message
   * @throws MessagingException
   * @throws AddressException
   * @throws NoSuchProviderException
   */
  public static MimeMessage createMimeMessage(
      Session session,
      String from,
      String[] to,
      String subject,
      String content,
      DataSource[] attachments) {

    logger.debug(
        "Creates a mime message with {} attachments",
        (attachments == null) ? 0 : attachments.length);

    try {
      MimeMessage message = new MimeMessage(session);

      if (from != null) {
        message.setSender(new InternetAddress(from));
      }

      if (subject != null) {
        message.setSubject(subject, "UTF-8");
      }

      if (to != null) {
        for (String toAdr : to) {
          message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAdr));
        }
      }

      if (attachments == null || attachments.length == 0) {
        // Setup a plain text message
        message.setContent(content, "text/plain; charset=UTF-8");

      } else {
        // Setup a multipart message
        Multipart multipart = new MimeMultipart();
        message.setContent(multipart);

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/plain; charset=UTF-8");
        multipart.addBodyPart(messageBodyPart);

        // Add attachments, if any
        if (attachments != null) {
          for (DataSource attachment : attachments) {
            BodyPart attatchmentBodyPart = new MimeBodyPart();
            attatchmentBodyPart.setDataHandler(new DataHandler(attachment));
            attatchmentBodyPart.setFileName(attachment.getName());
            multipart.addBodyPart(attatchmentBodyPart);
          }
        }
      }
      return message;

    } catch (AddressException e) {
      throw new RuntimeException(e);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
コード例 #24
0
ファイル: SendMailAdmin.java プロジェクト: vppai29/OnlineTest
  public int sendVerify(String name, String uname, String pass) {
    int i = 0;
    Properties properties = System.getProperties();
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.host", "smtp.gmail.com");
    // properties.put("mail.smtp.user", "*****@*****.**"); // User
    // name
    // properties.put("mail.smtp.password", "43993389"); // password

    properties.put("mail.smtp.port", "587");
    properties.put("mail.smtp.auth", "true");
    Session session =
        Session.getInstance(
            properties,
            new javax.mail.Authenticator() {
              @Override
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("*****@*****.**", "ratindia"); // Specify
                // the
                // Username
                // and the
                // PassWord
              }
            });

    try {
      final MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject("Authentication Success : Confirmation E-mail");

      MimeMultipart multipart = new MimeMultipart("related");
      String workingDir = System.getProperty("user.dir");

      String path = workingDir.substring(0, (workingDir.length() - 3));

      BodyPart messageBodyPart = new MimeBodyPart();
      String htmltext =
          "<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml'><head><title>...::: RAT Online Academic Panel :::...</title></head><body><table style='background:url(cid:bg) no-repeat;'><tr><td><div id='top'  style='margin-top:-60px;height:100px;font-family: Lucida Calligraphy; background-color: #336699; color:cyan;'><img src='cid:logo' height='100' style='float:left'><h1 align='right'>Road Ahead Technologies&nbsp;</h1><h2 align='right'>Online Academic Panel&nbsp;&nbsp;</h2></div><br /><div id='info' style='font-family: Consolas;color:black;'><h1 style='font-family: Lucida Calligraphy; text-align:center'>Authentication Success</h1><table style='font-family: Cambria;' >Dear "
              + name
              + ",<br /><br/>Your account has been succesfully authenticated at Road Ahead Technologies Online Panel.<br /><br />Your Login credentials are as follows : <br /><br /><strong>Username : </strong>&nbsp;"
              + uname
              + "<br /><strong>Password : </strong>&nbsp;"
              + pass
              + "<br /><br/>You need to change login password on first to panel.<br/>Thanks,<br/>Admin<br/>RAT Online Panel<br/><br/></table></div><table align='center'><tr><br /><br /><br /><td><img src='cid:imagea' height=100 />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td><img src='cid:imageb' height=100/></td></tr></table></form><br /><br /><table align=center width=700px style='font-size:20px;'><tr><td><a href='http://*****:*****@ RAT 2014 <br/><br />Developed By <a href='http://www.facebook.com/ggauravag'>Gaurav Agarwal</a></div></td></tr></table></body></html>";
      messageBodyPart.setContent(htmltext, "text/html");
      multipart.addBodyPart(messageBodyPart);

      DataSource fds = new FileDataSource(path + "webapps\\OnlineTest\\images\\rat.png");
      DataSource fds1 = new FileDataSource(path + "webapps\\OnlineTest\\images\\s1.jpg");
      DataSource fds2 = new FileDataSource(path + "webapps\\OnlineTest\\images\\s2.jpg");
      DataSource fds3 = new FileDataSource(path + "webapps\\OnlineTest\\images\\bg.jpg");

      messageBodyPart = new MimeBodyPart();
      messageBodyPart.setDataHandler(new DataHandler(fds));
      messageBodyPart.addHeader("Content-ID", "<logo>");
      multipart.addBodyPart(messageBodyPart);

      messageBodyPart = new MimeBodyPart();
      messageBodyPart.setDataHandler(new DataHandler(fds1));
      messageBodyPart.addHeader("Content-ID", "<imagea>");
      multipart.addBodyPart(messageBodyPart);

      messageBodyPart = new MimeBodyPart();
      messageBodyPart.setDataHandler(new DataHandler(fds2));
      messageBodyPart.addHeader("Content-ID", "<imageb>");
      multipart.addBodyPart(messageBodyPart);

      messageBodyPart = new MimeBodyPart();
      messageBodyPart.setDataHandler(new DataHandler(fds3));
      messageBodyPart.addHeader("Content-ID", "<bg>");
      multipart.addBodyPart(messageBodyPart);

      message.setContent(multipart);

      new Thread(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    Transport.send(message);
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                }
              })
          .start();

      System.out.println("Sent message successfully from admin....");
      session = null;
      i = 1;
    } catch (MessagingException mex) {
      mex.printStackTrace();
      return i;
    }
    return i;
  }
コード例 #25
0
ファイル: EnvioMail.java プロジェクト: gvilchis23/eservice
  @SuppressWarnings("unchecked")
  public void sendMail(
      String subject, String mensajeHtml, List<DestinoMailTO> correosDestino, String plantilla) {
    try {
      Properties props = PropertiesService.getInstance().getProperties("eMail.properties");
      Session session = Session.getDefaultInstance(props, null);

      MimeMultipart rootMultiParte = new MimeMultipart("mixed");
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));
      message.setSubject(subject);
      message.setContent(rootMultiParte);
      for (DestinoMailTO obj : correosDestino) {
        if (obj.getEmail() != null && obj.getNombreDestinatario() != null) {
          message.addRecipient(
              Message.RecipientType.TO,
              new InternetAddress(obj.getEmail(), obj.getNombreDestinatario()));
        } else if (obj.getEmail() != null) {
          message.addRecipient(Message.RecipientType.TO, new InternetAddress(obj.getEmail()));
        }
      }

      MimeMultipart multiParte = new MimeMultipart("related");
      BodyPart bodyPart = new MimeBodyPart();
      bodyPart.setContent(multiParte);
      rootMultiParte.addBodyPart(bodyPart);

      bodyPart = new MimeBodyPart();
      bodyPart.setDataHandler(new DataHandler(new FileDataSource(mensajeHtml)));
      String contenido = mensajeHtml;
      bodyPart.setContent(contenido, "text/html");
      multiParte.addBodyPart(bodyPart);
      try {

        String embebidos =
            PropertiesService.getInstance()
                .getPropertie("eMailPlantillas.properties", "enbed." + plantilla);
        if (embebidos != null) {
          String[] splited = embebidos.split("\\|");
          ArrayList<String> attachmentsEnbebidos = new ArrayList<String>();
          for (String string : splited) {
            attachmentsEnbebidos.add(string);
          }

          String[] aux;
          File file;
          if (attachmentsEnbebidos != null)
            for (String enbeds : attachmentsEnbebidos) {
              aux = enbeds.split(" ");
              String sss = "plantillas" + File.separator + plantilla + File.separator + aux[1];
              URL path = EnvioMail.class.getClassLoader().getResource(sss);
              file = new File(path.getPath());
              bodyPart = new MimeBodyPart();
              bodyPart.setHeader("Content-ID", "<" + aux[0] + ">");
              bodyPart.setDataHandler(new DataHandler(new FileDataSource(file.getAbsolutePath())));
              multiParte.addBodyPart(bodyPart);
            }
        }
      } catch (ClassCastException e) {
        String attachmentsEnbebidos =
            (String)
                PropertiesService.getInstance()
                    .getPropertie("eMailPlantillas.properties", "enbed." + plantilla);

        String[] aux;
        File file;
        if (!Validator.isEmpty(attachmentsEnbebidos)) {
          aux = attachmentsEnbebidos.split(" ");
          String sss = "plantillas" + File.separator + plantilla + File.separator + aux[1];
          String path = EnvioMail.class.getClassLoader().getResource(sss).getPath();
          file = new File(path);
          bodyPart = new MimeBodyPart();
          bodyPart.setHeader("Content-ID", "<" + aux[0] + ">");
          bodyPart.setDataHandler(new DataHandler(new FileDataSource(file.getAbsolutePath())));
          multiParte.addBodyPart(bodyPart);
        }
      }

      try {

        String attaches =
            PropertiesService.getInstance()
                .getPropertie("eMailPlantillas.properties", "attachment." + plantilla);

        if (attaches != null) {
          String[] attachm = attaches.split("\\|");
          ArrayList<String> attachments = new ArrayList<String>();

          for (String string : attachm) {
            attachments.add(string);
          }
          String[] aux;
          File file;
          if (attachments != null) {
            for (String attach : attachments) {
              aux = attach.split(" ");
              String fileStirng =
                  "plantillas" + File.separator + plantilla + File.separator + aux[0];
              String path = EnvioMail.class.getClassLoader().getResource(fileStirng).getPath();
              URL url = new File(path).toURL();
              BodyPart adjunto = new MimeBodyPart();
              adjunto.setDataHandler(new DataHandler(url));
              adjunto.setFileName(aux[1]);
              rootMultiParte.addBodyPart(adjunto);
            }
          }
        }
      } catch (ClassCastException e) {
        String attachments =
            (String)
                PropertiesService.getInstance()
                    .getPropertie("eMailPlantillas.properties", "attachment." + plantilla);
        String[] aux;
        File file;
        if (!Validator.isEmpty(attachments)) {
          aux = attachments.split(" ");

          String fileStirng = "plantillas" + File.separator + plantilla + File.separator + aux[0];
          String path = EnvioMail.class.getClassLoader().getResource(fileStirng).getPath();
          URL url = new File(path).toURL();
          BodyPart adjunto = new MimeBodyPart();
          adjunto.setDataHandler(new DataHandler(url));
          adjunto.setFileName(aux[1]);
          rootMultiParte.addBodyPart(adjunto);
        }
      }

      Transport.send(message);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #26
0
  public static void sendNotification() {

    // Recipient's email ID needs to be mentioned.
    String[] toMailerList = configProps.getProperty("To").split(",");
    System.out.println(configProps.getProperty("To"));
    String[] ccMailerList = configProps.getProperty("CC").split(",");
    System.out.println(configProps.getProperty("CC"));
    final String username = configProps.getProperty("UserName");
    final String password = configProps.getProperty("Password");
    String from = configProps.getProperty("From");

    Properties props = new Properties();

    props.put("mail.smtp.host", "mail.quickflix.com.au");
    props.put("mail.smtp.port", "25");

    Session session = Session.getInstance(props);
    try {
      // Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(session);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));

      javax.mail.internet.InternetAddress[] addressTo =
          new javax.mail.internet.InternetAddress[toMailerList.length];

      for (int i = 0; i < toMailerList.length; i++) {
        addressTo[i] = new javax.mail.internet.InternetAddress(toMailerList[i]);
      }
      message.setRecipients(javax.mail.Message.RecipientType.TO, addressTo);

      javax.mail.internet.InternetAddress[] addressCC =
          new javax.mail.internet.InternetAddress[ccMailerList.length];
      for (int i = 0; i < ccMailerList.length; i++) {
        addressCC[i] = new javax.mail.internet.InternetAddress(ccMailerList[i]);
      }
      message.setRecipients(javax.mail.Message.RecipientType.CC, addressCC);
      // Set Subject: header field
      message.setSubject("Test Data Expiry Alert"); // ("Quickflix Titles are Exceeded  .... ");

      // Create the message part
      BodyPart messageBodyPart = new MimeBodyPart();

      // Fill the message
      messageBodyPart.setContent(
          "Hi, <br><br>"
              + configProps.getProperty("body")
              + "<br><br>Thanks,<br>Offshore Team<br><br>",
          "text/html; charset=utf-8");
      // Create a multipart message
      Multipart multipart = new MimeMultipart();
      // Set text message part
      multipart.addBodyPart(messageBodyPart);
      message.setContent(multipart);
      // Send message
      Transport.send(message);
      System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
  }
コード例 #27
0
  public static void envioCorreo(
      String destinatarios,
      String asunto,
      String detalle,
      List<File> listAdjunto,
      Parametro parametro)
      throws Exception {

    Properties properties = new Properties();
    properties.put("mail.smtp.host", parametro.getMailSmtpHost());
    properties.put("mail.smtp.port", parametro.getMailSmtpPort());
    properties.put("mail.smtp.auth", parametro.getMailSmtpAuth());

    properties.put("mail.smtp.ssl.trust", parametro.getMailSmtpSslTrust());
    properties.put("mail.smtp.starttls.enable", parametro.getMailSmtpStartTlsEnable());

    Session session = Session.getInstance(properties, null);

    MimeMessage mensaje = new MimeMessage(session);
    mensaje.setFrom(new InternetAddress(parametro.getEmailEmisor()));

    try {
      mensaje.addRecipient(Message.RecipientType.TO, new InternetAddress(destinatarios));
      // Message.RecipientType.CC; con copia
      // Message.RecipientType.BCC; con copia oculta
    } catch (Exception e) {
      e.printStackTrace();
    }

    mensaje.setSubject(asunto);
    mensaje.setSentDate(new Date());

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(detalle, "text/html");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    if (listAdjunto != null && !listAdjunto.isEmpty()) {
      for (File adjunto : listAdjunto) {
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(adjunto)));
        messageBodyPart.setFileName(adjunto.getName());
        multipart.addBodyPart(messageBodyPart);
      }
    }

    mensaje.setContent(multipart);

    System.clearProperty("javax.net.ssl.keyStore");
    System.clearProperty("javax.net.ssl.keyStorePassword");
    System.clearProperty("javax.net.ssl.trustStore");
    System.clearProperty("javax.net.ssl.trustStorePassword");

    SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
    try {
      transport.connect(parametro.getEmailEmisor(), parametro.getPassEmail());
      transport.sendMessage(mensaje, mensaje.getAllRecipients());
    } finally {
      transport.close();
    }
  }
コード例 #28
0
  public static void sendReportAsMailBody(String filePath, String subject, String AttachmentSource)
      throws Throwable {

    File fis =
        new File(
            "C:\\SVN\\12 QuickflixProject\\QuickflixProject\\Results\\Chrome\\"
                + "Chrome_2015-03-25_15_54_34_292\\SummaryResults_2015-03-25_15_54_34_292.html");
    // File fis = new File(filePath);
    FileReader fileReader = new FileReader(fis);
    // jsoup code
    Document doc = Jsoup.parse(fis, "UTF-8", "http://example.com/");
    Element newsHeadlines = doc.getElementById("footer");
    Elements header = doc.select("head");
    String jsonStringBuffer =
        "<html>"
            + header.html()
            + "<body> <table id='footer'>"
            + newsHeadlines.html()
            + "</table></body></html>";
    Document newFooter = Jsoup.parse(jsonStringBuffer);
    Element remLogos = doc.getElementById("Logos");
    remLogos.remove();
    Element remFooter = doc.getElementById("footer");
    remFooter.remove();
    // **********
    BufferedReader reader = new BufferedReader(fileReader);
    StringBuffer stringBuffer = new StringBuffer();
    String line;
    while ((line = reader.readLine()) != null) {
      // String newLine[] = line.split("(?<=footer).*?(?=</tfoot>)");
      String newLine[] = line.split("(?i)(<table id='footer'.*?>)(.+?)(</tfoot>)");
      // System.out.println(newLine[0]);
      /*String logoLess[]=newLine[0].split("(?i)(<table id='Logos'.*?>)(.+?)(main)");
      System.out.println(logoLess[0]);*/
      stringBuffer.append(newLine[0]);
    }
    // stringBuffer.append(stbfooter.toString());
    /*System.out.println("Contents of file:");
    System.out.println(stringBuffer.toString());*/
    fileReader.close();

    // Recipient's email ID needs to be mentioned.
    String[] toMailerList = configProps.getProperty("To").split(",");
    System.out.println(configProps.getProperty("To"));
    String[] ccMailerList = configProps.getProperty("CC").split(",");
    System.out.println(configProps.getProperty("CC"));
    final String username = configProps.getProperty("UserName");
    final String password = configProps.getProperty("Password");
    String from = configProps.getProperty("From");

    /*Properties props = new Properties();
    props.put("mail.smtp.host", "mail.quickflix.com.au");
    props.put("mail.smtp.port", "25");*/

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.socketFactory.fallback", "false");
    /*props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "465");*/
    props.put("mail.smtp.host", "smtp.office365.com");
    props.put("mail.smtp.port", "995");
    Session session =
        Session.getInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
              }
            });

    // Session session = Session.getInstance(props);
    try {
      // Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(session);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));

      javax.mail.internet.InternetAddress[] addressTo =
          new javax.mail.internet.InternetAddress[toMailerList.length];

      for (int i = 0; i < toMailerList.length; i++) {
        addressTo[i] = new javax.mail.internet.InternetAddress(toMailerList[i]);
      }
      message.setRecipients(javax.mail.Message.RecipientType.TO, addressTo);

      javax.mail.internet.InternetAddress[] addressCC =
          new javax.mail.internet.InternetAddress[ccMailerList.length];
      for (int i = 0; i < ccMailerList.length; i++) {
        addressCC[i] = new javax.mail.internet.InternetAddress(ccMailerList[i]);
      }
      message.setRecipients(javax.mail.Message.RecipientType.CC, addressCC);
      // Set Subject: header field
      message.setSubject(subject);

      // Create the message part
      BodyPart messageBodyPart = new MimeBodyPart();
      // Create the attachement part
      BodyPart AttachmentBodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource(AttachmentSource);
      AttachmentBodyPart.setDataHandler(new DataHandler(source));
      AttachmentBodyPart.setFileName("QuickflixReports.zip");
      // Fill the message
      messageBodyPart.setContent(
          newFooter.html() + stringBuffer.toString(), "text/html; charset=utf-8");
      // Create a multipart message
      Multipart multipart = new MimeMultipart();
      // Set Attachment part
      multipart.addBodyPart(AttachmentBodyPart);
      // Set text message part
      multipart.addBodyPart(messageBodyPart);
      message.setContent(multipart);
      // Send message
      Transport.send(message);
      System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
  }
コード例 #29
0
  public boolean sendMessage() {
    Properties properties = new Properties();
    properties.put("mail.smtp.host", mailHost);
    properties.put("mail.from", Source);
    Session session = Session.getInstance(properties, null);
    try {
      Message message = new MimeMessage(session);
      InternetAddress[] addressTO = null;
      if (this.Destination != null && this.Destination.length() != 0) {
        StringTokenizer TOList = getTokenizer(this.Destination);
        addressTO = new InternetAddress[TOList.countTokens()];
        for (int i = 0; i < addressTO.length; i++) {
          addressTO[i] = new InternetAddress(TOList.nextToken());
          message.addRecipient(Message.RecipientType.TO, addressTO[i]);
        }
      }

      if (this.MsgCC != null && this.MsgCC.length() != 0) {
        StringTokenizer CCList = getTokenizer(this.MsgCC);
        InternetAddress[] addressCC = new InternetAddress[CCList.countTokens()];
        for (int i = 0; i < addressCC.length; i++) {
          addressCC[i] = new InternetAddress(CCList.nextToken());
          message.addRecipient(Message.RecipientType.CC, addressCC[i]);
        }
      }
      message.setFrom(new InternetAddress(Source));
      message.setSubject(Subject);
      Content = getHtmlHeader() + Content + getHtmlFooter();
      Content = Content.replaceAll("\\{style\\}", MailStyle);

      BodyPart messageBodyPart = new MimeBodyPart();

      messageBodyPart.setText(Content);
      messageBodyPart.setContent(Content, "text/html");

      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);

      Iterator it = this.BinaryAttachments.iterator();
      while (it.hasNext()) {
        ByteArrayDataSource bads = (ByteArrayDataSource) it.next();

        messageBodyPart = new MimeBodyPart();
        // messageBodyPart.setDataHandler(new DataHandler(new FileDataSource("c:/test/tom.jpg")));
        messageBodyPart.setDataHandler(new DataHandler(bads));
        messageBodyPart.setFileName(bads.getName());

        multipart.addBodyPart(messageBodyPart);
      }
      message.setContent(multipart);

      Transport transport = session.getTransport(addressTO[0]);
      transport.addConnectionListener(new ConnectionHandler());
      transport.addTransportListener(new TransportHandler());
      transport.connect();
      transport.send(message);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
コード例 #30
0
ファイル: JavaMailMailer.java プロジェクト: ksen938/thundr
 private void addBody(Multipart multipart, String content, String contentType)
     throws MessagingException {
   BodyPart messageBodyPart = new MimeBodyPart();
   messageBodyPart.setContent(content, contentType);
   multipart.addBodyPart(messageBodyPart);
 }