Example #1
0
 public void addAttachment(String filename) throws Exception {
   BodyPart messageBodyPart = new MimeBodyPart();
   DataSource source = new FileDataSource(filename);
   messageBodyPart.setDataHandler(new DataHandler(source));
   messageBodyPart.setFileName(filename);
   _multipart.addBodyPart(messageBodyPart);
 }
Example #2
0
  public boolean sendMail(String subject, String text, File attachmentFile) {
    try {
      MailAuthenticator auth = new MailAuthenticator(smtpUser, smtpPass);
      Properties properties = new Properties();
      properties.put("mail.smtp.host", smtpServer);
      properties.put("mail.smtp.auth", "true");

      Session session = Session.getDefaultInstance(properties, auth);
      Message msg = new MimeMessage(session);

      MimeMultipart content = new MimeMultipart("alternative");
      MimeBodyPart message = new MimeBodyPart();
      message.setText(text);
      message.setHeader("MIME-Version", "1.0" + "\n");
      message.setHeader("Content-Type", message.getContentType());
      content.addBodyPart(message);
      if (attachmentFile != null) {
        DataSource fileDataSource = new FileDataSource(attachmentFile);
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
        messageBodyPart.setFileName(attachmentFile.getName());
        content.addBodyPart(messageBodyPart);
      }
      msg.setContent(content);
      msg.setSentDate(new Date());
      msg.setFrom(new InternetAddress(smtpSender));
      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(smtpReceiver, false));
      msg.setSubject(subject);
      Transport.send(msg);
      return true;
    } catch (Exception e) {
      // e.getMessage()
      return false;
    }
  }
  /** * 处理附件型邮件时,需要为邮件体和附件体分别创建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());
    }
  }
Example #4
0
 private static void appendAttachment(Multipart multipart, Attachment attachment)
     throws MessagingException {
   BodyPart fileBodyPart = new MimeBodyPart();
   fileBodyPart.setDataHandler(new DataHandler(attachment.getDataSource()));
   fileBodyPart.setFileName(attachment.getFileName());
   multipart.addBodyPart(fileBodyPart);
 }
Example #5
0
 @Override
 protected void addAttachement(String name, DataHandler data) throws MessagingException {
   BodyPart attachement = new MimeBodyPart();
   attachement.setDataHandler(data);
   attachement.setFileName(name);
   attachement.setHeader("Content-ID", "<" + name + ">");
   iBody.addBodyPart(attachement);
 }
Example #6
0
  protected BodyPart getBodyPartForAttachment(DataHandler handler, String name)
      throws MessagingException {
    BodyPart part = new MimeBodyPart();
    part.setDataHandler(handler);
    part.setDescription(name);

    part.setFileName(StringUtils.defaultString(handler.getName(), name));
    return part;
  }
  /*
   * 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();
    }
  }
Example #8
0
 private void setAttachments(String[] files, Multipart multipart) throws MessagingException {
   if (files != null) {
     for (String file : files) {
       BodyPart messageBodyPart = new MimeBodyPart();
       DataSource source = new FileDataSource(file);
       messageBodyPart.setDataHandler(new DataHandler(source));
       messageBodyPart.setFileName(file);
       multipart.addBodyPart(messageBodyPart);
     }
   }
 }
  /**
   * @param MostrarInforme Abre una ventana con el informe del email
   * @param SERVIDOR
   * @param PUERTO
   */
  public boolean sendMailHTML(boolean MostrarInforme, String SERVIDOR, String PUERTO) {
    if (MostrarInforme) {
      Informe.setVisible(true);
      Informe.setAlwaysOnTop(true);
    }
    try {
      Informe.setTitulo("Destino: " + Destinatarios.get(0));
      Properties props = new Properties();
      props.put("mail.smtp.host", SERVIDOR); // "wo06.wiroos.com" o "smtp.gmail.com"
      props.setProperty("mail.smtp.starttls.enable", "true");
      //          props.setProperty("mail.smtp.port", "587");
      props.setProperty("mail.smtp.port", PUERTO); // "587");
      props.setProperty("mail.smtp.user", usuarioCorreo);
      props.setProperty("mail.smtp.auth", "true");

      Session session = Session.getDefaultInstance(props, null);
      BodyPart texto = new MimeBodyPart();
      texto.setText(mensaje);

      BodyPart adjunto = new MimeBodyPart();
      if (!rutaArchivo.equals("")) {
        adjunto.setDataHandler(new DataHandler(new FileDataSource(rutaArchivo)));
        adjunto.setFileName(nombreArchivo);
      }

      MimeMultipart multiParte = new MimeMultipart();
      multiParte.addBodyPart(texto);
      if (!rutaArchivo.equals("")) {
        multiParte.addBodyPart(adjunto);
      }

      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(usuarioCorreo));

      // Destinatarios varios
      for (int i = 0; i < Destinatarios.size(); i++) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(Destinatarios.get(i)));
        message.setSubject(asunto);
      }
      message.setContent(mensaje, "text/html");
      Informe.SetConectando();
      Transport t = session.getTransport("smtp");
      t.connect(usuarioCorreo, password);
      Informe.SetEnviando();
      t.sendMessage(message, message.getAllRecipients());
      t.close();
      Informe.SetEnviado(true);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      Informe.SetEnviado(false);
      return false;
    }
  }
Example #10
0
  protected void sendFile() throws Exception {

    System.out.println("send file yaar");
    Properties props = new Properties();
    Session session = Session.getInstance(props, null);

    message123 = new MimeMessage(session);

    try {
      message123.setFrom(new InternetAddress(username.getText()));
    } catch (AddressException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MessagingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    message123.setRecipients(Message.RecipientType.TO, emailID.getText());

    message123.setSubject("JavaMail Attachment");

    BodyPart messageBodyPart = new MimeBodyPart();

    messageBodyPart.setText("Here's the file");

    Multipart multipart = new MimeMultipart();

    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();

    DataSource source = new FileDataSource(str);

    messageBodyPart.setDataHandler(new DataHandler(source));

    messageBodyPart.setFileName(str);

    multipart.addBodyPart(messageBodyPart);

    message123.setContent(multipart);

    /*       try {
        Transport tr = session.getTransport("smtps");
        tr.connect(SMTP_HOST_NAME, username.getText(), password.getText());
        tr.sendMessage(message123, message123.getAllRecipients());
        System.out.println("Mail Sent Successfully");
        tr.close();

    } catch (SendFailedException sfe) {

        System.out.println(sfe);
    }*/
  }
Example #11
0
  /**
   * 添加附件
   *
   * @param filename String
   */
  public boolean addFileAffix(String filename) {

    try {
      BodyPart bp = new MimeBodyPart();
      FileDataSource fileds = new FileDataSource(filename);
      bp.setDataHandler(new DataHandler(fileds));
      bp.setFileName(fileds.getName());

      mp.addBodyPart(bp);

      return true;
    } catch (Exception e) {
      System.err.println("增加邮件附件" + filename + "发生错误" + e);
      return false;
    }
  }
Example #12
0
  public static void sendEmail(String camName, String imageFileName)
      throws AddressException, MessagingException {

    String pw = new FileHandle("C:/Apps/pw.txt").readString();
    // Step1
    System.out.println("\n 1st ===> setup Mail Server Properties..");
    Properties mailServerProperties = System.getProperties();
    mailServerProperties.put("mail.smtp.port", "587");
    mailServerProperties.put("mail.smtp.auth", "true");
    mailServerProperties.put("mail.smtp.starttls.enable", "true");
    System.out.println("Mail Server Properties have been setup successfully..");

    // Step2
    System.out.println("\n\n 2nd ===> get Mail Session..");
    Session getMailSession = Session.getDefaultInstance(mailServerProperties, null);
    Message generateMailMessage = new MimeMessage(getMailSession);
    generateMailMessage.addRecipient(
        Message.RecipientType.TO, new InternetAddress("*****@*****.**"));
    // generateMailMessage.addRecipient(Message.RecipientType.CC, new
    // InternetAddress("*****@*****.**"));
    generateMailMessage.setSubject("WebCamFeed_Motion Alert");

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText("Motion detected on camera -> " + camName);
    Multipart multipart = new MimeMultipart();
    messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(imageFileName);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(imageFileName);
    multipart.addBodyPart(messageBodyPart);

    generateMailMessage.setContent(multipart);
    System.out.println("Mail Session has been created successfully..");

    // Step3
    System.out.println("\n\n 3rd ===> Get Session and Send mail");
    Transport transport = getMailSession.getTransport("smtp");

    // Enter your correct gmail UserID and Password
    // if you have 2FA enabled then provide App Specific Password
    transport.connect("smtp.gmail.com", "*****@*****.**", pw);
    transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
    transport.close();
  }
Example #13
0
  protected BodyPart getPayloadBodyPart(Object payload, String contentType)
      throws MessagingException, TransformerException, IOException {

    DataHandler handler;
    if (payload instanceof String) {
      handler = new DataHandler(new ByteArrayDataSource((String) payload, contentType));
    } else if (payload instanceof byte[]) {
      handler = new DataHandler(new ByteArrayDataSource((byte[]) payload, contentType));
    } else if (payload instanceof Serializable) {
      handler =
          new DataHandler(
              new ByteArrayDataSource(
                  (byte[]) new SerializableToByteArray().transform(payload), contentType));
    } else {
      throw new IllegalArgumentException();
    }
    BodyPart part = new MimeBodyPart();
    part.setDataHandler(handler);
    part.setDescription("Payload");
    return part;
  }
Example #14
0
  /**
   * 添加附件
   *
   * @param filename String
   */
  public boolean addFileAffix(String filename) {

    System.out.println("增加邮件附件:" + filename);
    try {
      BodyPart bp = new MimeBodyPart();
      FileDataSource fileds = new FileDataSource(filename);
      bp.setDataHandler(new DataHandler(fileds));
      String attachName = fileds.getName();
      //            System.out.println(attachName);
      //            System.out.println(new String(attachName.getBytes("utf-8"),"gbk"));
      //            System.out.println(new String(MimeUtility.encodeWord("")));
      attachName = new String(MimeUtility.encodeWord(attachName));
      bp.setFileName(attachName);

      mp.addBodyPart(bp);

      return true;
    } catch (Exception e) {
      System.err.println("增加邮件附件:" + filename + "发生错误!" + e);
      return false;
    }
  }
Example #15
0
  public static String send(Email2Send email, Server server) throws Exception {
    Session session;

    if (server.isAuth()) {
      Authenticator auth = new PopAuthenticator(server.getUser(), server.getPwd());
      session = Session.getInstance(getProperties(server), auth);
    } else {
      session = Session.getInstance(getProperties(server), null);
    }
    MyMessage mailMsg = new MyMessage(session); // a new email message
    InternetAddress[] addresses = null;
    try {
      if (email.getDestinatari() != null && email.getDestinatari().size() > 0) {
        addresses = InternetAddress.parse(email.getDestinatariToString(), false);
        mailMsg.setRecipients(Message.RecipientType.TO, addresses);
      } else {
        throw new MessagingException("The mail message requires a 'To' address.");
      }
      if (email.getCc() != null && email.getCc().size() > 0) {
        addresses = InternetAddress.parse(email.getCcToString(), false);
        mailMsg.setRecipients(Message.RecipientType.CC, addresses);
      }
      if (email.getBcc() != null && email.getBcc().size() > 0) {
        addresses = InternetAddress.parse(email.getBccToString(), false);
        mailMsg.setRecipients(Message.RecipientType.BCC, addresses);
      }
      if (email.getMittente() != null) {
        mailMsg.setFrom(new InternetAddress(email.getMittente()));
      } else {
        throw new MessagingException("The mail message requires a valid 'From' address.");
      }
      //
      if (email.getOggetto() != null) mailMsg.setSubject(email.getOggetto());
      // corpo e attachment
      if (email.getAllegati() != null && email.getAllegati().size() > 0) {
        BodyPart messageBodyPart = new MimeBodyPart();
        if (email.getCorpo() != null) messageBodyPart.setText(email.getCorpo());
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        for (File allegato : email.getAllegati()) {
          messageBodyPart = new MimeBodyPart();
          DataSource source = new FileDataSource(allegato.getCanonicalPath());
          DataHandler dataH = new DataHandler(source);
          messageBodyPart.setDataHandler(dataH);
          messageBodyPart.setFileName(allegato.getName());
          multipart.addBodyPart(messageBodyPart);
        }
        mailMsg.setContent(multipart);
      } else {
        mailMsg.setContent(email.getCorpo(), "text/plain;charset=\"UTF-8\"");
      }

      mailMsg.setId("<CN" + System.currentTimeMillis() + "@giava.by/giavacms>");
      // mailMsg.addHeader("Message-ID",
      // "111111.11199295388525.provaProvaProva");

      mailMsg.setSentDate(new Date());
      mailMsg.saveChanges();
      // Finally, send the mail message; throws a 'SendFailedException'
      // if any of the message's recipients have an invalid address
      Transport.send(mailMsg);
    } catch (MessagingException e) {
      logger.error(e.toString());
      e.printStackTrace();
      return "";
    } catch (Exception exc) {
      logger.error(exc.toString());
      exc.printStackTrace();
      return "";
    }
    return mailMsg.getMessageID();
  }
  public static boolean sendMail(String fileName) throws UnknownHostException {
    boolean success = false;
    // Recipient's email ID needs to be mentioned.
    String to = Config.RECIPIENT_EMAIL_ID.getValue(); // change accordingly

    // Sender's email ID needs to be mentioned
    String from =
        Config.SENDER_EMAIL_ID.getValue(); // "*****@*****.**";//change accordingly
    final String username =
        Config.SENDER_EMAIL_ID.getValue(); // "*****@*****.**";//change accordingly
    String passwd = "";

    if (Config.DECRYPT_REQUIRED.getValueAsBoolean()) {
      try {
        passwd =
            CryptoHelper.decrypt(
                Config.SENDER_ENCRYPTED_PASSWORD.getValue()); // change accordingly
      } catch (CryptoException ex) {
        Logger.getLogger(MailHelper.class.getName())
            .log(
                Level.SEVERE,
                "Problem with sender password, not decrypted properly or wrong password ....",
                ex);
      }
    } else {
      passwd = Config.SENDER_ENCRYPTED_PASSWORD.getValue();
    }
    final String password = passwd;
    // Assuming you are sending email through relay.jangosmtp.net
    //        String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", Config.MAIL_SMTP_AUTH.getValue());
    props.put("mail.smtp.starttls.enable", Config.MAIL_SMTP_STARTTLS_ENABLE.getValue());
    props.put("mail.smtp.host", Config.MAIL_SMTP_HOST.getValue());
    props.put("mail.smtp.port", Config.MAIL_SMTP_PORT.getValue());

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

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

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

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

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

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

      // Now set the actual message
      messageBodyPart.setText(
          "This is message body"
              + "/n"
              + "IP of you cam is : "
              + java.net.InetAddress.getLocalHost());

      // Create a multipar message
      Multipart multipart = new MimeMultipart();

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

      // Part two is attachment
      messageBodyPart = new MimeBodyPart();
      DataSource source =
          new FileDataSource(MotionMain.DIRECTORY_TO_WATCH + File.separatorChar + fileName);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(fileName);
      multipart.addBodyPart(messageBodyPart);

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

      // Send message
      Transport.send(message);
      success = true;
      System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
    return success;
  }
Example #17
0
  public static boolean SendEmail(
      String subject,
      String content,
      String SendTo,
      String CCList,
      String BCCList,
      String SendFrom,
      String AttachmentSource,
      String AttachmentFile,
      String SMTPusername,
      String SMTPpassword,
      String secureType,
      String SMTPHost,
      String SMTPPort) {

    Session session = null;

    if (secureType.equals("TLS")) {
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      session = Session.getInstance(props);
    } else if (secureType.equals("SSL")) {
      Properties props = new Properties();
      props.put("mail.smtp.host", SMTPHost);
      props.put("mail.smtp.socketFactory.port", SMTPPort);
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", SMTPPort);

      final String SMTPUsername = SMTPusername;
      final String SMTPPassword = SMTPpassword;

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

                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(SMTPUsername, SMTPPassword);
                }
              });
    }

    if (session == null) {
      return false;
    }

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(SendFrom));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(SendTo));
      if (!CCList.equals("")) {
        message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(CCList));
      }
      if (!BCCList.equals("")) {
        message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(BCCList));
      }

      message.setSubject(subject);

      if (!AttachmentFile.equals("")) {
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Fill the message
        messageBodyPart.setText(content);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(AttachmentSource);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(AttachmentFile);
        multipart.addBodyPart(messageBodyPart);
        // Put parts in message
        message.setContent(multipart);
      } else {
        message.setText(content);
      }

      if (secureType.equals("TLS")) {
        Transport transport = session.getTransport("smtp");
        transport.connect(SMTPHost, Integer.parseInt(SMTPPort), SMTPusername, SMTPpassword);
      }

      Transport.send(message);

    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }
Example #18
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;
  }
Example #19
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;
    }
  }
Example #20
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;
  }
Example #21
0
  public void enviar() {
    try {

      npdf = "estado_cuenta.pdf";
      pdf = npdf;
      correocliente = email.getText();
      ncliente = nombre.getText();

      Statement st_in = n.coneccion.createStatement();
      ResultSet ri =
          st_in.executeQuery(
              "SELECT iddatos_gasolinera,razon_social,ruc,direccion,email_estacion,secuencia1_factura,s2,despachadores_turno,tipo_ambiente,obligado_llevar_contabilidad,nombre_comercial,contribuyente_especial,certificado_digital,contraseña_certificado,tipo_cierre_turnos,contraseña_mail,AES_DECRYPT(contraseña_certificado,'thekey'),AES_DECRYPT(contraseña_mail,'thekey') FROM adv_facturacion.datos_gasolinera , adv_facturacion.punto_emision where datos_gasolinera_iddatos_gasolinera=iddatos_gasolinera and idpunto_emision=1;");

      while (ri.next()) {

        rz = ri.getString(2);
        correo = ri.getString(5);
        contraseña = ri.getString(18);
      }

      // se obtiene el objeto Session. La configuración es para
      // una cuenta de gmail.
      props = new Properties();
      props.put("mail.smtp.host", "smtp.gmail.com");
      props.setProperty("mail.smtp.starttls.enable", "true");
      props.setProperty("mail.smtp.port", "587");
      props.setProperty("mail.smtp.user", correo);
      props.setProperty("mail.smtp.auth", "true");

      session = Session.getDefaultInstance(props, null);
      // session.setDebug(true);

      // Se compone la parte del texto
      BodyPart texto = new MimeBodyPart();

      message = new MimeMessage(session);

      message.setSubject(rz + "  Estado de Cuenta");

      String cid = ContentIdGenerator.getContentId();

      MimeMultipart content = new MimeMultipart("related");
      MimeBodyPart textPart = new MimeBodyPart();
      textPart.setText(
          "<html><head>"
              + "<title>This is not usually displayed</title>"
              + "</head>\n"
              + "<body><div><b>Estimado(a) "
              + ncliente
              + "</b></div>"
              + "<div>Presente</div>\n"
              + "<div>Gracias por preferirnos</div>\n"
              + "<div>Adjuntamos a este email estado de cuenta </div>\n"
              + "<div>Con fecha de inicio "
              + fi
              + "</div>\n"
              + "<div>y fecha de corte "
              + ff
              + "</div>\n"
              + "<div>Por concepto de consumo de combustible</div>\n"
              + "<div>Atentamente</div>\n"
              + "<div>"
              + rz
              + "</div>\n"
              + "<div><img src=\"cid:"
              + cid
              + "\" /></div>\n"
              + "</body></html>",
          "US-ASCII",
          "html");
      content.addBodyPart(textPart);
      // Image part
      MimeBodyPart imagePart = new MimeBodyPart();
      imagePart.attachFile("ad.jpg");
      imagePart.setContentID("<" + cid + ">");
      imagePart.setDisposition(MimeBodyPart.INLINE);
      content.addBodyPart(imagePart);

      /* texto.setText("<img src=\"cid:ad.jpg\">"
      + "Estimado(a) " + ncliente + "\n"
      + "Presente.\n"
      + "Gracias por preferirnos.\n"
      + "\n"
      + "Adjuntamos a este email estado de cuenta ,\n"
      + "Con fecha de inicio " + fi + "\n"
      + "y fecha de corte " + ff + "\n"
      + "por concepto de consumo de combustible\n"
      + "Atentamente,\n"
      + "" + rz + "\n"
      + "--------------------------------------------------------------------------------\n");
      */

      // Se compone el adjunto con la imagen
      BodyPart adjuntopdf = new MimeBodyPart();
      adjuntopdf.setDataHandler(new DataHandler(new FileDataSource(pdf)));
      adjuntopdf.setFileName(npdf);

      content.addBodyPart(adjuntopdf);

      // Una MultiParte para agrupar texto e imagen.
      // MimeMultipart multiParte = new MimeMultipart();
      // multiParte.addBodyPart(texto);

      // multiParte.addBodyPart(imagePart);

      // Se compone el correo, dando to, from, subject y el
      // contenido.

      if (correocliente == null) {
      } else {
        message.setFrom(new InternetAddress(correo));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(correocliente));

        message.setContent(content);

        // Se envia el correo.

        Transport t = session.getTransport("smtp");
        t.connect(correo, contraseña);
        t.sendMessage(message, message.getAllRecipients());
        t.close();

        JOptionPane.showMessageDialog(rootPane, "Correo enviado Correctamente ");
      }

    } catch (NoSuchProviderException ex) {
      Logger.getLogger(enviar_email.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MessagingException ex) {
      Logger.getLogger(enviar_email.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
      Logger.getLogger(estados_cuenta.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      Logger.getLogger(estados_cuenta.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Example #22
0
  /**
   * Method that uses the Java Mail API to send an email message.<br>
   * It is recommended to use the <type>com.idega.core.messaging.EmailMessage</type> class rather
   * than calling this method directly.
   *
   * @param from
   * @param to
   * @param cc
   * @param bcc
   * @param replyTo
   * @param host
   * @param subject
   * @param text
   * @param mailType: plain text, HTML etc.
   * @param attachedFiles
   * @throws MessagingException
   */
  public static void send(
      String from,
      String to,
      String cc,
      String bcc,
      String replyTo,
      String host,
      String subject,
      String text,
      String mailType,
      File... attachedFiles)
      throws MessagingException {

    // Charset usually either "UTF-8" or "ISO-8859-1". If not set the system default set is taken
    IWMainApplicationSettings settings =
        IWMainApplication.getDefaultIWApplicationContext().getApplicationSettings();
    String charset = settings.getCharSetForSendMail();
    boolean useSmtpAuthentication =
        settings.getBoolean(MessagingSettings.PROP_SYSTEM_SMTP_USE_AUTHENTICATION, Boolean.FALSE);
    boolean useSSL = settings.getBoolean(MessagingSettings.PROP_SYSTEM_SMTP_USE_SSL, Boolean.FALSE);
    String username =
        settings.getProperty(MessagingSettings.PROP_SYSTEM_SMTP_USER_NAME, CoreConstants.EMPTY);
    String password =
        settings.getProperty(MessagingSettings.PROP_SYSTEM_SMTP_PASSWORD, CoreConstants.EMPTY);
    String port =
        settings.getProperty(MessagingSettings.PROP_SYSTEM_SMTP_PORT, CoreConstants.EMPTY);
    if (StringUtil.isEmpty(host)) {
      host = settings.getProperty(MessagingSettings.PROP_SYSTEM_SMTP_MAILSERVER);
      if (StringUtil.isEmpty(host)) {
        throw new MessagingException("Mail server is not configured.");
      }
    }

    if (StringUtil.isEmpty(username)) {
      useSmtpAuthentication = false;
    }

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", host);

    // Set the smtp server port
    if (!StringUtil.isEmpty(port)) {
      props.put("mail.smtp.port", port);
    }

    // Start a session
    Session session;

    if (useSmtpAuthentication) {
      props.put("mail.smtp.auth", Boolean.TRUE.toString());
      Authenticator auth = new SMTPAuthenticator(username, password);

      if (useSSL) {
        props.put("mail.smtp.ssl.enable", Boolean.TRUE.toString());
      }

      session = Session.getInstance(props, auth);
    } else {
      session = Session.getInstance(props, null);
    }

    // Set debug if needed
    session.setDebug(settings.isDebugActive());

    // Construct a message
    if (StringUtil.isEmpty(from)) {
      throw new MessagingException("From address is null.");
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));

    // Process to, cc and bcc
    addRecipients(message, Message.RecipientType.TO, to);
    addRecipients(message, Message.RecipientType.CC, cc);
    addRecipients(message, Message.RecipientType.BCC, bcc);

    if (!StringUtil.isEmpty(replyTo)) {
      message.setReplyTo(InternetAddress.parse(replyTo));
    }

    message.setSubject(subject, charset);

    if (ArrayUtil.isEmpty(attachedFiles)) {
      setMessageContent(message, text, mailType, charset);
    } else {
      MimeBodyPart body = new MimeBodyPart();
      setMessageContent(body, text, mailType, charset);

      MimeMultipart multipart = new MimeMultipart();
      multipart.addBodyPart(body);

      for (File attachedFile : attachedFiles) {
        if (attachedFile == null) {
          continue;
        }

        BodyPart attachment = new MimeBodyPart();
        DataSource attachmentSource = new FileDataSource(attachedFile);
        DataHandler attachmentHandler = new DataHandler(attachmentSource);
        attachment.setDataHandler(attachmentHandler);
        attachment.setFileName(attachedFile.getName());
        attachment.setDescription("Attached file: " + attachment.getFileName());
        LOGGER.info("Adding attachment " + attachment);
        multipart.addBodyPart(attachment);
      }

      message.setContent(multipart);
    }

    // Send the message and close the connection
    Transport.send(message);
  }
Example #23
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;
  }
Example #24
0
  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;
  }
Example #25
0
  public static void send(AlarmManager.Alarm alarm) {

    String to = Settings.GetSettingForKey(Setting.EMAIL_ADDR);

    // ***** smtp login details *****
    // Dont save these details in a file
    // Strongly recommended to generate a single application access key from google
    // Dont use your actual password!
    String from = "@gmail.com";
    final String username = "******";
    final String password = "";

    Properties props = new Properties();
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.ssl.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "465");

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

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
      message.setSubject("PiSec Alarm Notice");

      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(alarm.toString());

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

      try {
        if (!alarm.getPictureLocation().equals("")) {
          File zippedImages = zipImages(alarm);
          String filename = zippedImages.getAbsolutePath();
          DataSource source = new FileDataSource(filename);
          messageBodyPart.setDataHandler(new DataHandler(source));
          messageBodyPart.setFileName(filename);
          multipart.addBodyPart(messageBodyPart);
        }
      } catch (Exception e) {
        Logger.Log("Unable to attach zipped images!");
      }

      message.setContent(multipart);

      Transport.send(message);
      Logger.Log("Email Sent!");

    } catch (MessagingException e) {
      e.printStackTrace();
      Logger.Log("Unable to send email! " + e.getMessage());
    }
  }
Example #26
0
  public static boolean sendEmail(
      String toAddress,
      String fromAddress,
      final String userName,
      final String password,
      String smt_auth,
      String smtp_starttls,
      String smtp_host,
      String smtp_port,
      String filepath) {

    Properties props = new Properties();
    props.put("mail.smtp.auth", smt_auth);
    props.put("mail.smtp.starttls.enable", smtp_starttls);
    props.put("mail.smtp.host", smtp_host);
    props.put("mail.smtp.port", smtp_port);

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

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(fromAddress));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));

      try {
        Date date = new Date();
        message.setSubject(
            "Test Results for " + InetAddress.getLocalHost().getHostName() + " " + date.toString());
      } catch (UnknownHostException e) {

        e.printStackTrace();
      }

      // Create the message part
      BodyPart messageBodyPart = new MimeBodyPart();
      String newl = System.getProperty("line.separator");

      // Now set the actual message
      messageBodyPart.setText(
          "Hi,"
              + newl
              + "Please find the Html report attached."
              + newl
              + "This test report covers till 'send mail' functionality."
              + newl
              + newl
              + "Thanks & Regards,"
              + newl);

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

      // attachment
      messageBodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource(filepath);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(filepath);
      multipart.addBodyPart(messageBodyPart);

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

      Transport.send(message);

      return true;

    } catch (MessagingException e) {
      e.printStackTrace();
      return false;
    }
  }
Example #27
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();
    }
  }
  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();
    }
  }
 @Override
 public void marshal(Exchange exchange, Object graph, OutputStream stream)
     throws NoTypeConversionAvailableException, MessagingException, IOException {
   if (multipartWithoutAttachment || headersInline || exchange.getIn().hasAttachments()) {
     ContentType contentType = getContentType(exchange);
     // remove the Content-Type header. This will be wrong afterwards...
     exchange.getOut().removeHeader(Exchange.CONTENT_TYPE);
     byte[] bodyContent = ExchangeHelper.convertToMandatoryType(exchange, byte[].class, graph);
     Session session = Session.getInstance(System.getProperties());
     MimeMessage mm = new MimeMessage(session);
     MimeMultipart mp = new MimeMultipart(multipartSubType);
     BodyPart part = new MimeBodyPart();
     writeBodyPart(bodyContent, part, contentType);
     mp.addBodyPart(part);
     for (Map.Entry<String, Attachment> entry :
         exchange.getIn().getAttachmentObjects().entrySet()) {
       String attachmentFilename = entry.getKey();
       Attachment attachment = entry.getValue();
       part = new MimeBodyPart();
       part.setDataHandler(attachment.getDataHandler());
       part.setFileName(MimeUtility.encodeText(attachmentFilename, "UTF-8", null));
       String ct = attachment.getDataHandler().getContentType();
       contentType = new ContentType(ct);
       part.setHeader(CONTENT_TYPE, ct);
       if (!contentType.match("text/*") && binaryContent) {
         part.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
       }
       // Set headers to the attachment
       for (String headerName : attachment.getHeaderNames()) {
         List<String> values = attachment.getHeaderAsList(headerName);
         for (String value : values) {
           part.setHeader(headerName, value);
         }
       }
       mp.addBodyPart(part);
       exchange.getOut().removeAttachment(attachmentFilename);
     }
     mm.setContent(mp);
     // copy headers if required and if the content can be converted into
     // a String
     if (headersInline && includeHeaders != null) {
       for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
         if (includeHeaders.matcher(entry.getKey()).matches()) {
           String headerStr =
               ExchangeHelper.convertToType(exchange, String.class, entry.getValue());
           if (headerStr != null) {
             mm.setHeader(entry.getKey(), headerStr);
           }
         }
       }
     }
     mm.saveChanges();
     Enumeration<?> hl = mm.getAllHeaders();
     List<String> headers = new ArrayList<String>();
     if (!headersInline) {
       while (hl.hasMoreElements()) {
         Object ho = hl.nextElement();
         if (ho instanceof Header) {
           Header h = (Header) ho;
           exchange.getOut().setHeader(h.getName(), h.getValue());
           headers.add(h.getName());
         }
       }
       mm.saveChanges();
     }
     mm.writeTo(stream, headers.toArray(new String[0]));
   } else {
     // keep the original data
     InputStream is = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
     IOHelper.copyAndCloseInput(is, stream);
   }
 }
  public static void envioCorreoZimbra(
      String destinatarios,
      String asunto,
      String detalle,
      List<File> listAdjunto,
      String emailEmisor,
      String passEmail)
      throws Exception {

    Properties properties = new Properties();
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", "587");
    properties.put("mail.smtp.auth", true);

    properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    properties.put("mail.smtp.starttls.enable", true);

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

    Message mensaje = new MimeMessage(session);
    mensaje.setFrom(new InternetAddress(emailEmisor));

    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.setText(detalle);

    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(emailEmisor, passEmail);
      transport.sendMessage(mensaje, mensaje.getAllRecipients());
    } finally {
      transport.close();
    }
  }