@Override
  public void run() {
    LOGGER.info("***********Inside send e-Mail Thread************");
    LOGGER.info("Sending email to:: E-mail Address::" + emailModel.getToaddess());
    Session mailSession = createSmtpSession();
    mailSession.setDebug(true);
    List<String> toAddresses = new ArrayList<String>();

    try {
      Transport transport = mailSession.getTransport();
      MimeMessage message = new MimeMessage(mailSession);

      message.setSubject(emailModel.getSubject());
      message.setFrom(new InternetAddress(emailModel.getFromAddress()));
      message.setContent(emailModel.getContent(), "text/html");

      toAddresses.add(emailModel.getToaddess());
      transport.connect();
      Iterator<String> itr = toAddresses.iterator();
      while (itr.hasNext()) {
        String toAddress = (String) itr.next();
        message.addRecipients(Message.RecipientType.TO, toAddress);
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
      }
      LOGGER.info("Successfully sent email to:: E-mail Address::" + emailModel.getToaddess());
    } catch (MessagingException e) {
      LOGGER.error("Cannot Send email", e);
    }
  }
示例#2
0
  /**
   * Sends an email out
   *
   * @param fromAddress
   * @param toAddresses
   * @param strSubject
   * @param strMsg
   */
  public void sendMail(
      String fromAddress,
      String strReplyTo,
      String[] toAddresses,
      String strSubject,
      String strMsg) {
    try {
      Properties props = new Properties();
      props.put("mail.smtp.host", SMTP_HOST);
      Session s = Session.getInstance(props, null);

      MimeMessage message = new MimeMessage(s);

      InternetAddress from = new InternetAddress(fromAddress);
      message.setFrom(from);

      InternetAddress[] addressTo = new InternetAddress[toAddresses.length];
      for (int i = 0; i < toAddresses.length; i++) {
        addressTo[i] = new InternetAddress(toAddresses[i]);
      }
      message.addRecipients(RecipientType.BCC, addressTo);

      message.setSubject(strSubject);
      message.setText(strMsg);
      if (strReplyTo != null) {
        InternetAddress[] iAddress = new InternetAddress[] {new InternetAddress(strReplyTo)};
        message.setReplyTo(iAddress);
      }
      Transport.send(message);
    } catch (Exception e) {
      throw new WickerException(e);
    }
  }
示例#3
0
  public void sendMailWithCalendar(
      String receivers, String subject, String body, String attachment) {
    log.info("Sending mail");
    try {
      Authenticator authenticator =
          new Authenticator(serverDetails.userName, serverDetails.password);
      Session session = Session.getDefaultInstance(properties, authenticator);
      MimeMessage message = new MimeMessage(session);

      message.setFrom(new InternetAddress(serverDetails.userName));
      message.addRecipients(Message.RecipientType.TO, receivers);
      message.setSubject(subject);

      MimeBodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(body);

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

      messageBodyPart = new MimeBodyPart();
      messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
      messageBodyPart.setHeader("Content-ID", "calendar_message");
      messageBodyPart.setDataHandler(
          new DataHandler(
              new ByteArrayDataSource(Files.readAllBytes(Paths.get(attachment)), "text/calendar")));
      multipart.addBodyPart(messageBodyPart);
      message.setContent(multipart);
      Transport.send(message);
      log.info("Mail sent");
    } catch (Exception e) {
      log.severe("Could not send mail!" + e.getMessage());
    }
  }
示例#4
0
  private static void addRecipients(
      MimeMessage message, RecipientType recipientType, String addresses)
      throws MessagingException {
    if (StringUtil.isEmpty(addresses)) {
      return;
    }

    addresses = addresses.replace(CoreConstants.SEMICOLON, CoreConstants.COMMA);
    message.addRecipients(recipientType, InternetAddress.parse(addresses));
  }
  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);
    }
  }
示例#6
0
  /**
   * Create an empty MimeMessage object with all properties set
   *
   * @param from Sender address
   * @param replyTo Reply-to address (null to omit)
   * @param to Array of target addresses
   * @param cc Array of CC addresses - or null
   * @param subject Subject
   */
  private static MimeMessage createMessage(
      String from, String replyTo, String[] to, String[] cc, String subject)
      throws MessagingException {
    Properties p = new Properties();
    p.setProperty("mail.transport.protocol", "smtp");
    p.setProperty("mail.smtp.host", smtpHost);
    p.setProperty("mail.from", from);
    Session s = Session.getInstance(p);
    MimeMessage mm = new MimeMessage(s);

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

    if (cc != null) {
      InternetAddress[] aiaCC = new InternetAddress[cc.length];
      for (int i = 0; i < aiaCC.length; ++i) {
        aiaCC[i] = new InternetAddress(cc[i]);
      }
      mm.addRecipients(Message.RecipientType.CC, aiaCC);
    }

    if (replyTo != null) {
      InternetAddress[] aiaReplyTo = new InternetAddress[1];
      aiaReplyTo[0] = new InternetAddress(replyTo);
      mm.setReplyTo(aiaReplyTo);
    }

    mm.setFrom(new InternetAddress(from));
    mm.setSubject(subject, "UTF-8");
    mm.setSentDate(new Date());

    return mm;
  }
示例#7
0
  public void sendEmail(EmailBuilder builder) {
    // 收件人电子邮箱
    String to = builder.getReceiver();

    // 发件人电子邮箱
    String from = builder.getSender();

    // 获取系统属性
    Properties properties = System.getProperties();

    // 设置邮件服务器
    properties.setProperty("mail.smtp.host", builder.getHost());
    properties.put("mail.smtp.port", builder.getPort());
    properties.put("mail.smtp.auth", builder.authNeeded());

    // 获取默认session对象
    Session session =
        Session.getDefaultInstance(
            properties,
            new Authenticator() {
              public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, builder.getToken()); // 发件人邮件用户名、密码
              }
            });

    try {
      // 创建默认的 MimeMessage 对象
      MimeMessage message = new MimeMessage(session);

      // Set From: 头部头字段
      message.setFrom(new InternetAddress(from));

      message.addRecipients(
          Message.RecipientType.TO,
          new InternetAddress[] {new InternetAddress(to), new InternetAddress(to)});
      // Set Subject: 头部头字段
      message.setSubject(builder.getTitle());

      // 设置消息体
      message.setText(builder.getContent());

      // 发送消息
      Transport.send(message);
      System.out.println("Sent message successfully....from Java Mail");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
  }
示例#8
0
  private static MimeMessage createMessage(
      String from, String[] to, String subject, MimeMultipart content) throws MessagingException {
    Session session = Session.getInstance(System.getProperties());
    session.setDebug(true);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));

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

    message.setSubject(subject);
    message.setContent(content);
    message.setHeader("X-Mailer", "iComp");
    message.setSentDate(new Date());
    return message;
  }
示例#9
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;
  }
示例#10
0
  public static void sendEmail(String email, String id)
      throws MessagingException, UnsupportedEncodingException {

    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("Traffic Generation Request #" + id + " has received");

    message.setContent(
        "Hi Sir/Madam, \n\n Your traffic generation request #"
            + id
            + " has been received by DMLab@UMN. \n You will be notified via email "
            + email
            + " , when we finish our processing.\n\n Please be patient. If you have any inquries, please send email to [email protected]. \n\n Thanks, \n DMLab@UMN",
        "text/plain");

    InternetAddress[] mntgAddress = new InternetAddress[1];
    mntgAddress[0] =
        new InternetAddress(
            "*****@*****.**",
            "Minnesota Traffic Generator"); // here we set our email alias and the desired display
    // name
    InternetAddress customer_email = new InternetAddress(email); // customer email

    message.addRecipient(Message.RecipientType.TO, customer_email);

    message.addRecipients(Message.RecipientType.CC, mntgAddress);
    message.addRecipients(Message.RecipientType.BCC, mntgAddress);

    message.setFrom(mntgAddress[0]);
    message.setReplyTo(mntgAddress);
    message.setSender(mntgAddress[0]);

    transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

    Address[] recipientsTo = message.getRecipients(Message.RecipientType.TO);
    Address[] recipientsCC = message.getRecipients(Message.RecipientType.CC);
    Address[] recipientsBCC = message.getRecipients(Message.RecipientType.BCC);

    Address[] allRecipients =
        new Address[recipientsTo.length + recipientsCC.length + recipientsBCC.length];
    int allIndex = 0;
    for (int i = 0; i < recipientsTo.length; ++i, ++allIndex) {
      allRecipients[allIndex] = recipientsTo[i];
    }
    for (int i = 0; i < recipientsCC.length; ++i, ++allIndex) {
      allRecipients[allIndex] = recipientsCC[i];
    }
    for (int i = 0; i < recipientsBCC.length; ++i, ++allIndex) {
      allRecipients[allIndex] = recipientsBCC[i];
    }

    transport.sendMessage(message, allRecipients);

    transport.close();

    //  InternetAddress notifyAddress = new InternetAddress("*****@*****.**", "Admin MailList");
    // //here we set our email alias and the desired display name
    // sendEmail(mntgAddress[0], notifyAddress,                "Traffic request #" + id + " has just
    // been submitted by user " + email + ".", email);

    /*
     * InternetAddress notifyAddress3 = new
     * InternetAddress("*****@*****.**", "Mohamed Mokbel"); //here we set
     * our email alias and the desired display name
     * sendEmail(mntgAddress[0], notifyAddress3, "Traffic request #" + id +
     * " has just been submitted by user " + email + ".", email);
     *
     */

  }
  /**
   * This method is used to send emails to the agency
   *
   * @param invoices
   */
  @Override
  public void sendInvoicesViaEmail(List<ContractsGrantsInvoiceDocument> invoices)
      throws AddressException, MessagingException {
    LOG.debug("sendInvoicesViaEmail() starting.");

    Properties props = getConfigProperties();

    // Get session
    Session session = Session.getInstance(props, null);
    for (ContractsGrantsInvoiceDocument invoice : invoices) {
      List<InvoiceAddressDetail> invoiceAddressDetails = invoice.getInvoiceAddressDetails();
      for (InvoiceAddressDetail invoiceAddressDetail : invoiceAddressDetails) {
        if (ArConstants.InvoiceTransmissionMethod.EMAIL.equals(
            invoiceAddressDetail.getInvoiceTransmissionMethodCode())) {

          // KFSTI-48 Refactor to retrieve the note through noteService
          Note note = noteService.getNoteByNoteId(invoiceAddressDetail.getNoteId());

          if (ObjectUtils.isNotNull(note)) {

            MimeMessage message = new MimeMessage(session);

            // From Address
            String sender =
                parameterService.getParameterValueAsString(
                    ContractsGrantsInvoiceEmailReportsBatchStep.class,
                    ArConstants.CG_INVOICE_FROM_EMAIL_ADDRESS);
            message.setFrom(new InternetAddress(sender));
            // To Address
            CustomerAddress customerAddress = invoiceAddressDetail.getCustomerAddress();
            String recipients = customerAddress.getCustomerEmailAddress();
            if (StringUtils.isNotEmpty(recipients)) {
              InternetAddress[] recipientAddress = {new InternetAddress(recipients)};
              message.addRecipients(Message.RecipientType.TO, recipientAddress);
            } else {
              LOG.warn("No recipients indicated.");
            }

            // The Subject
            String subject =
                parameterService.getParameterValueAsString(
                    ContractsGrantsInvoiceEmailReportsBatchStep.class,
                    ArConstants.CG_INVOICE_EMAIL_SUBJECT);
            String bodyText =
                parameterService.getParameterValueAsString(
                    ContractsGrantsInvoiceEmailReportsBatchStep.class,
                    ArConstants.CG_INVOICE_EMAIL_BODY);
            Map<String, String> map = new HashMap<String, String>();
            getEmailParameterList(map, invoice, customerAddress);
            subject = replaceValuesInString(subject, map);
            bodyText = replaceValuesInString(bodyText, map);
            message.setSubject(subject);
            if (StringUtils.isEmpty(subject)) {
              LOG.warn("Empty subject being sent.");
            }

            // Now the message body.
            // create and fill the first message part
            MimeBodyPart body = new MimeBodyPart();
            body.setText(bodyText);

            // create and fill the second message part
            MimeBodyPart attachment = new MimeBodyPart();
            // Use setText(text, charset), to show it off !
            // create the Multipart and its parts to it
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(body);
            try {
              ByteArrayDataSource ds =
                  new ByteArrayDataSource(
                      note.getAttachment().getAttachmentContents(), "application/pdf");
              attachment.setDataHandler(new DataHandler(ds));
              attachment.setFileName(note.getAttachment().getAttachmentFileName());
              multipart.addBodyPart(attachment);
            } catch (IOException ex) {
              LOG.error("problem during AREmailServiceImpl.sendInvoicesViaEmail()", ex);
            }

            // add the Multipart to the message
            message.setContent(multipart);

            // Finally, send the message!
            Transport.send(message);
          }
        }
      }
      invoice.setMarkedForProcessing(ArConstants.INV_RPT_PRCS_SENT);
      documentService.updateDocument(invoice);
    }
  }
  private void sendMail(
      String to,
      String cc,
      String bcc,
      String subject,
      String msgContent,
      List<EmailAttachmentBean> emailAttachmentList)
      throws Exception {

    PropertyFileReader propertyFileReader = PropertyFileReader.getInstance();
    doInit();
    msgContent +=
        "<br/><br/><br/><br/> This is a system generated email, do not reply to this email id.";
    MimeMessage message = new MimeMessage(session);
    // Set From: header field of the header.
    message.setFrom(new InternetAddress(emailId));
    // Set To: header field of the header.
    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    if (cc != null && cc.length() != 0)
      message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));

    if (bcc != null && bcc.length() != 0) {
      bcc = bcc.replaceAll(";", ",");
      message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
    }
    // Set Subject: header field
    message.setSubject(subject);
    /* Start Here */
    // Create the message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    // Fill the message
    messageBodyPart.setText(
        "<pre style='font-size:16px;font-family: Calibri'>" + msgContent + "</pre>", null, "html");
    // Create a multipar message
    Multipart multipart = new MimeMultipart();

    // please don't delete this code before deleting please let me know @Siva Sankar
    // this code is for sending email with attachment
    if (emailAttachmentList != null && !emailAttachmentList.isEmpty()) {
      for (EmailAttachmentBean emailAttachmentBean : emailAttachmentList) {
        MimeBodyPart attachmentPart = new MimeBodyPart();

        DataSource source =
            new ByteArrayDataSource(emailAttachmentBean.getFileContent(), "text/html");
        attachmentPart.setDataHandler(new DataHandler(source));
        attachmentPart.setFileName(emailAttachmentBean.getFileName());

        multipart.addBodyPart(attachmentPart);
      }
      /*if (attachmentpos != null && attachmentpos.contains("&&&&")) {
      	MimeBodyPart attachmentPart = new MimeBodyPart();
      	String[] strArray = attachmentpos.split("&&&&");
      	String attchFileContent = strArray[0];
      	String attchFileName = strArray[1].trim();
      	DataSource source = new FileDataSource(attchFileContent);
      	attachmentPart.setDataHandler(new DataHandler(source));
      	attachmentPart.setFileName(attchFileName);
      	multipart.addBodyPart(attachmentPart);
      }*/
    }
    // Set text message part
    multipart.addBodyPart(messageBodyPart);
    // Send the complete message parts
    message.setContent(multipart);
    // Send message
    Transport.send(message);
    /* End Here */

    System.out.println("Sent message successfully.... Sent to " + to);
  }
示例#13
0
  public boolean send() {
    try {
      // creamos las propiedades del mail
      Properties propiedades = System.getProperties();
      propiedades.put("mail.smtp.host", hostSmtp);
      propiedades.put("mail.smtp.auth", "true");
      propiedades.put("mail.smtp.port", puertoSMTP);

      // creamos la sesión para enviar el mail
      SMTPAuthentication auth = new SMTPAuthentication();
      Session mailSesion = Session.getInstance(propiedades, auth);

      // creamos el mensaje
      MimeMessage mens = new MimeMessage(mailSesion);

      // Definimos la dirección del remitente
      mens.setFrom(new InternetAddress(this.origen));

      // creamos un array de las direcciones de los destinatarios
      InternetAddress[] addressTo = new InternetAddress[this.direcciones.size()];
      for (int i = 0; i < this.direcciones.size(); i++) {
        addressTo[i] = new InternetAddress((String) this.direcciones.get(i));
      }

      // definimos los destinatarios
      mens.addRecipients(Message.RecipientType.TO, addressTo);

      // definiemos la fecha de envio
      mens.setSentDate(new Date());

      // Definimos el asunto
      mens.setSubject(asunto);

      Multipart multipart = new MimeMultipart();
      MimeBodyPart texto = new MimeBodyPart();
      texto.setContent(this.mensaje, "text/html");
      multipart.addBodyPart(texto);

      if (this.rutaAdjunto != null) {
        BodyPart adjunto = new MimeBodyPart();
        adjunto.setDataHandler(new DataHandler(new FileDataSource(this.rutaAdjunto)));
        adjunto.setFileName(this.nombreAdjunto);
        multipart.addBodyPart(adjunto);
      }

      // Definimos el cuerpo del mensaje
      mens.setContent(multipart);

      // Creamos el objeto transport con el método
      Transport transporte = mailSesion.getTransport("smtp");

      // enviamos el correo
      transporte.send(mens);

    } catch (AddressException ex) {
      ex.printStackTrace();
      return false;
    } catch (SendFailedException ex) {
      ex.printStackTrace();
      return false;
    } catch (MessagingException ex) {
      ex.printStackTrace();
      return false;
    } catch (Exception ex) {
      ex.printStackTrace();
      return false;
    }
    return true;
  }
示例#14
0
  public static String doSendMail(String mmsg, String toAddress, String subject, String filnme)
      throws Exception {
    String status = "N";
    try {
      String fromAddress = "*****@*****.**";
      String messages = "" + mmsg;

      MailSSLSocketFactory sf = new MailSSLSocketFactory();
      sf.setTrustAllHosts(true);
      Properties properties = System.getProperties();
      properties.put("mail.smtp.host", "mail.nic.in");
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.ssl.enable", "true");

      properties.put("mail.smtp.port", "465");
      properties.put("mail.smtp.ssl.socketFactory", sf);
      Session session = Session.getInstance(properties);
      MimeMessage msg = new MimeMessage(session);

      msg.setFrom(new InternetAddress(fromAddress));
      msg.addRecipients(Message.RecipientType.TO, toAddress);
      msg.setSubject(subject);
      msg.setText(messages);

      Message message = new MimeMessage(session);

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

      // Set To: header field of the header.
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));

      // Set Subject: header field
      message.setSubject(subject);

      BodyPart messageBodyPart = new MimeBodyPart();

      // Now set the actual message
      messageBodyPart.setText(messages);
      Multipart multipart = new MimeMultipart();

      // Set text message part
      multipart.addBodyPart(messageBodyPart);

      // Part two is attachment
      messageBodyPart = new MimeBodyPart();
      // String filename = "C:/JHRKHDCTAX_Settlement_20140721.xml";
      String filename = "C:/" + filnme;
      System.out.println(filename);
      DataSource source = new FileDataSource(filename);
      messageBodyPart.setDataHandler(new DataHandler(source));
      // messageBodyPart.setFileName("JHRKHDCTAX_Settlement_20140721.xml");
      messageBodyPart.setFileName(filnme);
      multipart.addBodyPart(messageBodyPart);

      // Send the complete message parts
      message.setContent(multipart);

      Transport tr = session.getTransport("smtp");
      tr.connect("mail.nic.in", "*****@*****.**", "Vz#$5d9*pnK");
      tr.sendMessage(message, message.getAllRecipients());
      tr.close();
      status = "Y";
    } catch (AddressException ex) {
      System.out.println(ex.getMessage());
      throw new Exception("Address not Valid");
    } catch (MessagingException ex) {
      System.out.println(ex.getMessage());
      throw new Exception("Mail sending fail " + ex.getMessage());
    } catch (Exception e) {
      throw new Exception("Mail sending fail " + e.getMessage());
    }
    return status;
  }
示例#15
0
  public static void main(String args[]) throws Exception {
    try {
      // Get system properties
      Properties props = new Properties();

      try {
        props.load(new FileInputStream("config.properties"));
      } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      } catch (IOException e1) {
        // TODO Auto-generated catch block
        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");

      String host = props.getProperty("host");
      final String sender = props.getProperty("username");
      final String pwd = props.getProperty("passwoed");

      Session session =
          Session.getInstance(
              props,
              new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(sender, pwd); // change
                  // accordingly
                }
              });

      // Get a Store object that implements the specified protocol.
      Store store = session.getStore("imaps");

      // Connect to the current host using the specified username and
      // password.
      store.connect(host, sender, pwd);

      // Create a Folder object corresponding to the given name.
      Folder folder = store.getFolder("inbox");

      // Open the Folder.
      folder.open(Folder.READ_WRITE);

      System.out.println("-------- Oracle JDBC Connection Testing ------");

      try {

        Class.forName("oracle.jdbc.driver.OracleDriver");

      } catch (ClassNotFoundException e) {

        System.out.println("Where is your Oracle JDBC Driver?");
        e.printStackTrace();
        return;
      }

      System.out.println("Oracle JDBC Driver Registered!");

      Connection connection = null;
      Statement stmt = null;
      String msg_subject = null;
      String msg_content = null;
      String msg_endofmail = null;
      String from_Email_Address = null;
      Statement stmt2 = null;
      try {
        connection =
            DriverManager.getConnection(
                props.getProperty("database"),
                props.getProperty("dbuser"),
                props.getProperty("dbpassword"));
        // STEP 4: Execute a query
        System.out.println("Creating statement..in Request Code 1.");
        stmt = connection.createStatement();
        System.out.println("Creating statement..in Request Code 2.");
        String preQuery =
            "select T.MSG_SUBJECT,t.MSG_CONTENT,t.MSG_ENDOFMAIL,T.MSG_TO_BE_SENT_TO from TEMP_RESPONSE_FOR_SYSREQUEST t where T.PROCESS_FLAG = 'N'";
        System.out.println("Creating statement..in Request Code 3." + preQuery);
        ResultSet rs1 = stmt.executeQuery(preQuery);
        System.out.println("Creating statement..in Request Code 4.");
        // STEP 5: Extract data from result set
        while (rs1.next()) {
          msg_subject = rs1.getString("MSG_SUBJECT");
          msg_content = rs1.getString("MSG_CONTENT");
          msg_endofmail = rs1.getString("MSG_ENDOFMAIL");
          from_Email_Address = rs1.getString("MSG_TO_BE_SENT_TO");
        }

        // STEP 6: Clean-up environment
        System.out.println("Fetching Records...");
        // message[i].setFlag(Flags.Flag.DELETED, true);
        try {
          System.out.println("Creating statement..in from email address." + from_Email_Address);
          if (from_Email_Address != null) {

            System.out.println(" FROM_EMAIL_ADDRESS 5555 : " + from_Email_Address);
            System.out.println(" To_Email_Address 5555 : " + sender);

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(sender));
            // message.addRecipient(Message.RecipientType.TO,new
            // InternetAddress(from_Email_Address));
            message.addRecipients(
                Message.RecipientType.TO, (InternetAddress.parse(from_Email_Address)));

            message.setSubject(msg_subject);
            System.out.println(" msg_s1 : " + msg_subject);

            message.setContent(" " + msg_content + " " + msg_endofmail, "text/html");

            Transport.send(message);
            System.out.println("Alert message sent");
          }
        } catch (MessagingException e) {
          throw new RuntimeException(e);
        }

        stmt = connection.createStatement();

        String updateStatus = "update TEMP_RESPONSE_FOR_SYSREQUEST set PROCESS_FLAG = 'Y' ";
        ResultSet rs3 = stmt.executeQuery(updateStatus);

        stmt.close();
        connection.close();
      } catch (SQLException e) {

        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return;
      }

      if (connection != null) {
        System.out.println("You made it, take control your database now!");
      } else {
        System.out.println("Failed to make connection!");
      }

      folder.close(true);
      store.close();

    } catch (Exception e) {

      System.out.println("Message Failed! Check output console");
      e.printStackTrace();
      return;
    }
  }
示例#16
0
  @Override
  public void send(TreeMap<String, Object> pars) throws AddressException, MessagingException {
    boolean trace = true;

    String from = (String) pars.get("from");
    String recipient = (String) pars.get("recipient");
    String ccRecipient = (String) pars.get("ccrecipient");
    String bccRecipient = (String) pars.get("bccrecipient");
    String subject = (String) pars.get("subject");
    String messageText = (String) pars.get("messageText");
    String messageHtml = (String) pars.get("messageHtml");
    URL[] messageHtmlInline = (URL[]) pars.get("messageHtmlInline");
    URL[] attachments = (URL[]) pars.get("attachments");

    // Checks, if recipient is not the supervisor
    if (!recipient.equals((String) properties.get("supervisorEMail"))) {
      // Send enabled check
      if (!parseBoolean((String) properties.get("isSendMailEnabled"), false)) return;

      // Redirection check
      if (parseBoolean((String) properties.get("isSendMailRedirected"), false)) {
        // TRACE
        if (trace) {
          logService.log(LogService.LOG_INFO, "Setting redirection: ");
        }

        subject = "[redirect from: " + recipient + "] " + subject;
        String redirect = (String) properties.get("sendMailRedirectTo");
        if (isValidEMail(redirect)) recipient = redirect;
        else {
          // TRACE
          if (trace) {
            logService.log(LogService.LOG_INFO, "Sending mail to supervisor: ");
          }

          sendMailToSupervisor(
              "Invalid redirection e-mail address",
              "Invalid redirection e-mail address: " + redirect);
          return;
        }
      }
    }

    try {
      // SET default sender if undefined
      if (isEON(from)) from = (String) properties.get("sendMailFrom");

      // SET properties: get system props
      Properties props = System.getProperties();

      // GET configuration SMTP SERVER
      String smtp_server = (String) properties.get("smtpServer");
      if (isEON(smtp_server)) smtp_server = "localhost";

      // GET configuration USERNAME and PASSWORD
      final String smtp_username = (String) properties.get("smtpUsername");
      final String smtp_password = (String) properties.get("smtpPassword");

      // SET default mail props
      props.put("mail.smtp.host", smtp_server);
      props.put("mail.mime.charset", "utf-8");

      // SET other configuration mail props
      for (Enumeration e = properties.keys(); e.hasMoreElements(); ) {
        String key = (String) e.nextElement();
        if (!key.startsWith("mail.")) continue;
        props.put(key, (String) properties.get(key));
      }

      // If setted: TRUST ALL HOSTS
      if (parseBoolean((String) properties.get("isTrustAllHosts"), false)) {
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.socketFactory", sf);
      }

      // TRACE
      if (trace) {
        logService.log(LogService.LOG_INFO, "Setted all properties: ");
      }

      // Get mail session with authenticator
      Session session =
          Session.getInstance(
              props,
              new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(smtp_username, smtp_password);
                }
              });

      // -- Create and build a new message --
      final MimeMessage msg = new MimeMessage(session);

      // TRACE
      if (trace) {
        logService.log(LogService.LOG_INFO, "Message, setting From");
      }
      // -- Set the FROM field --
      msg.setFrom(new InternetAddress(from));

      // TRACE
      if (trace) {
        logService.log(LogService.LOG_INFO, "Message, setting Recipient");
      }
      // -- Set the TO field --
      msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));

      // TRACE
      if (trace) {
        logService.log(LogService.LOG_INFO, "Message, setting CCrecipient");
      }
      // -- Set the CC recipient
      if (ccRecipient != null && ccRecipient.length() > 0) {
        msg.addRecipients(Message.RecipientType.CC, InternetAddress.parse(ccRecipient, false));
      }

      // TRACE
      if (trace) {
        logService.log(LogService.LOG_INFO, "Message, setting BCCrecipient");
      }
      // -- Set the CC recipient
      if (bccRecipient != null && bccRecipient.length() > 0) {
        msg.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(bccRecipient, false));
      }

      // TRACE
      if (trace) {
        logService.log(LogService.LOG_INFO, "Message, setting Subject");
      }
      // -- Set the SUBJECT
      msg.setSubject(subject);

      // -- Set MIXED content
      EmailContentBuilder mailContentBuilder = new EmailContentBuilder();

      ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
      Thread.currentThread().setContextClassLoader(javax.mail.Session.class.getClassLoader());
      try {
        // TRACE
        if (trace) {
          logService.log(LogService.LOG_INFO, "Message, building MIXED content");
        }

        final Multipart mpMixed =
            mailContentBuilder.build(messageText, messageHtml, messageHtmlInline, attachments);
        msg.setContent(mpMixed);
        msg.setSentDate(new Date());

        // TRACE
        if (trace) {
          logService.log(LogService.LOG_INFO, "Message, SENDING E-mail");
        }

        // SEND message
        Transport.send(msg);
      } finally {
        Thread.currentThread().setContextClassLoader(oldCl);
      }

      // TRACE
      if (trace) {
        logService.log(
            LogService.LOG_INFO, "E-mail sent to: " + recipient + ", subject:" + subject);
      }
    } catch (SendFailedException e) {
      if (e.getValidSentAddresses() != null)
        for (Address vsa : e.getValidUnsentAddresses()) {
          logService.log(LogService.LOG_ERROR, "Sent: " + vsa.toString());
        }
      if (e.getValidUnsentAddresses() != null)
        for (Address vsa : e.getValidUnsentAddresses()) {
          logService.log(LogService.LOG_ERROR, "Not sent: " + vsa.toString());
        }
      if (e.getInvalidAddresses() != null)
        for (Address ia : e.getInvalidAddresses()) {
          logService.log(LogService.LOG_ERROR, "Invalid address: " + ia.toString());
        }

      logService.log(
          LogService.LOG_ERROR, "Failure sending e-mail to: " + recipient + " " + e.toString());
    } catch (Exception e) {
      e.printStackTrace();
      logService.log(
          LogService.LOG_ERROR, "Failure sending e-mail to: " + recipient + " " + e.toString());
    }
  }