Пример #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);
 }
Пример #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;
    }
  }
Пример #3
0
  /** * 处理附件型邮件时,需要为邮件体和附件体分别创建BodyPort对象 然后将其置入MimeMultipart对象中作为一个整体进行发送 */
  @Override
  protected void setContent(MimeMessage message) throws MailException {
    try {
      Multipart multipart = new MimeMultipart();
      // 文本
      BodyPart textBodyPart = new MimeBodyPart();
      multipart.addBodyPart(textBodyPart);
      textBodyPart.setContent(text, "text/html;charset=" + charset);

      // 附件
      for (File attachment : attachments) {
        BodyPart fileBodyPart = new MimeBodyPart();
        multipart.addBodyPart(fileBodyPart);
        FileDataSource fds = new FileDataSource(attachment);
        fileBodyPart.setDataHandler(new DataHandler(fds));
        // 中文乱码
        String attachmentName = fds.getName();
        fileBodyPart.setFileName(MimeUtility.encodeText(attachmentName));
      }
      // 内容
      message.setContent(multipart);
    } catch (Exception e) {
      new MailException(e.getMessage());
    }
  }
Пример #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);
 }
Пример #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);
 }
Пример #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;
  }
Пример #7
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);
     }
   }
 }
Пример #8
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);
    }*/
  }
  /**
   * @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;
    }
  }
  private void sendNewItems(String[][] itemsMatrix, Date firstDate, Date lastDate) {
    Multipart multipart = new MimeMultipart();

    Writer writer = generateCSV(itemsMatrix);

    Session session = getSession();
    String from = getFromAddress();

    Set<String> recipients = getRecipients();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    String firstDateStr = sdf.format(firstDate);
    String lastDateStr = sdf.format(lastDate);

    List<String> arguments = new ArrayList<String>();
    arguments.add(firstDateStr);
    arguments.add(lastDateStr);

    String messageText =
        "Please find attached the items that have been created in Digital Collections.";
    try {
      messageText = getMessageText("mail/newmail.txt", arguments.toArray(new String[0]));
    } catch (IOException e) {
      // Do nothing instead use default text;
    }
    try {
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));
      for (String to : recipients) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      }
      message.setSubject("New items in Digital Collections list");

      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(messageText);
      multipart.addBodyPart(messageBodyPart);

      messageBodyPart = new MimeBodyPart();
      messageBodyPart.setFileName("new_dspace_items.csv");
      messageBodyPart.setText(writer.toString());

      multipart.addBodyPart(messageBodyPart);

      message.setContent(multipart);
      Transport.send(message);
      LOGGER.info("Sent message successfully...");
    } catch (MessagingException e) {
      LOGGER.error("Error sending message", e);
    }
  }
Пример #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;
    }
  }
Пример #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();
  }
Пример #13
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;
    }
  }
Пример #14
0
  protected MimeMessage buildMessage(
      Collection<String> tos,
      Collection<String> ccs,
      Collection<String> bccs,
      Map<String, String> headers,
      String subject,
      String body)
      throws MailerException {

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

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

      Multipart mp = new MimeMultipart();

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

      mp.addBodyPart(messageBodyText);

      if (null != getAttachmentsFiles()) {

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

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

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

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

          mp.addBodyPart(messageAttachment);
        }
      }

      message.setContent(mp);

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

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

    return message;
  }
Пример #15
0
  /**
   * Creates a mime-message, multipart if attachements are supplied otherwise as plain text. Assumes
   * UTF-8 encoding for both subject and content.
   *
   * @param session, must be specified
   * @param from, can be null
   * @param to, can be null or empty
   * @param subject, can be null
   * @param content, must be specified
   * @param attachments, can be null or empty
   * @return the mime-message
   * @throws MessagingException
   * @throws AddressException
   * @throws NoSuchProviderException
   */
  public static MimeMessage createMimeMessage(
      Session session,
      String from,
      String[] to,
      String subject,
      String content,
      DataSource[] attachments) {

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

    try {
      MimeMessage message = new MimeMessage(session);

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

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

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

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

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

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

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

    } catch (AddressException e) {
      throw new RuntimeException(e);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
Пример #16
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);
    }
  }
Пример #17
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);
  }
Пример #18
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;
  }
Пример #19
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());
    }
  }
Пример #20
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;
    }
  }
  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();
    }
  }
  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();
    }
  }
Пример #23
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();
  }
Пример #24
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;
  }
Пример #25
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;
  }
Пример #26
0
  /**
   * This function will create the message used to invoke the fax job action.<br>
   * If this method returns null, the SPI will throw an UnsupportedOperationException.
   *
   * @param faxJob The fax job object containing the needed information
   * @param mailResourcesHolder The mail resources holder
   * @return The message to send (if null, the SPI will throw an UnsupportedOperationException)
   */
  @Override
  protected Message createSubmitFaxJobMessage(
      FaxJob faxJob, MailResourcesHolder mailResourcesHolder) {
    // get logger
    Logger logger = this.getLogger();

    // get target address
    String targetAddress = faxJob.getTargetAddress();

    // format TO value
    String toAddress = MessageFormat.format(this.mailAddressTemplate, new Object[] {targetAddress});
    logger.logDebug(new Object[] {"Formatted TO address: ", toAddress}, null);

    // format subject value
    String subject = MessageFormat.format(this.mailSubjectTemplate, new Object[] {targetAddress});
    logger.logDebug(new Object[] {"Formatted subject: ", subject}, null);

    // get session
    Session session = mailResourcesHolder.getSession();

    // create message
    Message message = new MimeMessage(session);

    // set from
    String from = faxJob.getSenderEmail();
    if ((from != null) && (from.length() > 0)) {
      try {
        message.setFrom(new InternetAddress(from));
      } catch (Exception exception) {
        throw new FaxException("Error while setting from address: " + from, exception);
      }
    }

    try {
      // add message recipient
      message.addRecipient(RecipientType.TO, new InternetAddress(toAddress));
    } catch (Exception exception) {
      throw new FaxException("Error while setting TO address: " + toAddress, exception);
    }

    try {
      // set message subject
      message.setSubject(subject);
    } catch (Exception exception) {
      throw new FaxException("Error while setting subject: " + subject, exception);
    }

    // create multi part
    Multipart multipart = new MimeMultipart();

    // init body part
    BodyPart messageFileAttachmentBodyPart = new MimeBodyPart();

    // init data source
    File file = faxJob.getFile();
    DataSource source = new FileDataSource(file);

    try {
      // set data
      messageFileAttachmentBodyPart.setDataHandler(new DataHandler(source));
      messageFileAttachmentBodyPart.setFileName(file.getName());

      // add to body
      multipart.addBodyPart(messageFileAttachmentBodyPart);

      // set content
      message.setContent(multipart);
    } catch (Exception exception) {
      throw new FaxException("Error while setting attachment.", exception);
    }

    return message;
  }
  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;
  }
Пример #28
0
  @SuppressWarnings("unchecked")
  public void sendMail(
      String subject, String mensajeHtml, List<DestinoMailTO> correosDestino, String plantilla) {
    try {
      Properties props = PropertiesService.getInstance().getProperties("eMail.properties");
      Session session = Session.getDefaultInstance(props, null);

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

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

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

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

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

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

      try {

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

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

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

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

      Transport.send(message);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 @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);
   }
 }
Пример #30
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;
    }
  }