Exemplo n.º 1
0
  @Override
  public void sendAsHtml(
      String subject, String html, Collection<String> recipients, Map<String, Object> htmlParams)
      throws Exception {
    Address[] addresses = new Address[recipients.size()];
    Iterator<String> iterator = recipients.iterator();
    int i = 0;
    while (iterator.hasNext()) {
      addresses[i] = new InternetAddress(iterator.next());
      i++;
    }

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

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

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

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

    Transport.send(message);
  }
Exemplo n.º 2
0
 public static BodyPart get(int value) {
   for (BodyPart bodyPart : values()) {
     if (bodyPart.getValue() == value) {
       return bodyPart;
     }
   }
   return null;
 }
Exemplo n.º 3
0
 @Override
 public void clear() {
   BodyPart bps[] = super.toArray(new BodyPart[super.size()]);
   super.clear();
   for (BodyPart bp : bps) {
     bp.setParent(null);
   }
 }
Exemplo n.º 4
0
 @Override
 public BodyPart remove(int index) {
   BodyPart bp = super.remove(index);
   if (bp != null) {
     bp.setParent(null);
   }
   return bp;
 }
Exemplo n.º 5
0
	public void Walk() {
		this.iCycle++;
		this.angleUppLegL = (((this.angleUppLegMax - this.angleUppLegMin) / 2f) * ((float) Math
				.sin(((((float) this.iCycle) / ((float) this.cycleLength)) * 2f) * 3.1415926535897931)))
				+ ((this.angleUppLegMax + this.angleUppLegMin) / 2f);
		this.angleUppLegR = (((this.angleUppLegMax - this.angleUppLegMin) / 2f) * ((float) Math
				.sin((((((float) this.iCycle) / ((float) this.cycleLength)) * 2f) * 3.1415926535897931) + 3.1415926535897931)))
				+ ((this.angleUppLegMax + this.angleUppLegMin) / 2f);
		this.angleLowLegL = (((this.angleLowLegMax - this.angleLowLegMin) / 2f) * ((float) Math
				.sin((((((float) this.iCycle) / ((float) this.cycleLength)) * 2f) * 3.1415926535897931)
						- (6.2831853071795862 * this.phaseDelay))))
				+ ((this.angleLowLegMax + this.angleLowLegMin) / 2f);
		this.angleLowLegR = (((this.angleLowLegMax - this.angleLowLegMin) / 2f) * ((float) Math
				.sin(((((((float) this.iCycle) / ((float) this.cycleLength)) * 2f) * 3.1415926535897931) + 3.1415926535897931)
						- (6.2831853071795862 * this.phaseDelay))))
				+ ((this.angleLowLegMax + this.angleLowLegMin) / 2f);
		this.position.x += this.speed;
		float num = (((float) (Math.cos((double) this.angleUppLegL) + Math
				.cos((double) this.angleLowLegL))) < ((float) (Math
				.cos((double) this.angleUppLegR) + Math
				.cos((double) this.angleLowLegR)))) ? ((float) (this.t2DUpperLeg.getHeight() * (Math
				.cos((double) this.angleUppLegL) + Math
				.cos((double) this.angleLowLegL))))
				: ((float) (this.t2DUpperLeg.getHeight() * (Math
						.cos((double) this.angleUppLegR) + Math
						.cos((double) this.angleLowLegR))));
		this.position.y = this.positionGround.y - num;
		this.angleUppArmL = (((this.angleUppArmMax - this.angleUppArmMin) / 2f) * ((float) Math
				.sin(((((float) this.iCycle) / ((float) this.cycleLength)) * 2f) * 3.1415926535897931)))
				+ ((this.angleUppArmMax + this.angleUppArmMin) / 2f);
		this.angleUppArmR = (((this.angleUppArmMax - this.angleUppArmMin) / 2f) * ((float) Math
				.sin((((((float) this.iCycle) / ((float) this.cycleLength)) * 2f) * 3.1415926535897931) + 3.1415926535897931)))
				+ ((this.angleUppArmMax + this.angleUppArmMin) / 2f);
		this.angleLowArmL = (((this.angleLowArmMax - this.angleLowArmMin) / 2f) * ((float) Math
				.sin((((((float) this.iCycle) / ((float) this.cycleLength)) * 2f) * 3.1415926535897931)
						+ (6.2831853071795862 * this.phaseDelay))))
				+ ((this.angleLowArmMax + this.angleLowArmMin) / 2f);
		this.angleLowArmR = (((this.angleLowArmMax - this.angleLowArmMin) / 2f) * ((float) Math
				.sin(((((((float) this.iCycle) / ((float) this.cycleLength)) * 2f) * 3.1415926535897931) + 3.1415926535897931)
						+ (6.2831853071795862 * this.phaseDelay))))
				+ ((this.angleLowArmMax + this.angleLowArmMin) / 2f);
		this.upperArmL.angle = -this.angleUppArmL;
		this.upperArmR.angle = -this.angleUppArmR;
		this.lowerArmL.angle = -this.angleLowArmL;
		this.lowerArmR.angle = -this.angleLowArmR;
		this.upperLegL.angle = -this.angleUppLegL;
		this.upperLegR.angle = -this.angleUppLegR;
		this.lowerLegL.angle = -this.angleLowLegL;
		this.lowerLegR.angle = -this.angleLowLegR;
		this.torso.angle = (0.08246681f * ((float) Math
				.sin(((((float) this.iCycle) / ((float) this.cycleLength)) * 2f) * 3.1415926535897931))) + 0.1090831f;
		for (BodyPart part : this.bodyPartList) {
			part.Update();
		}
		if (this.iCycle >= this.cycleLength) {
			this.iCycle = 0;
		}
	}
 private void clearIfBitesSelf() {
   boolean clear = false;
   for (BodyPart part : bodyParts) {
     if (snakeX == part.getX() && snakeY == part.getY()) {
       clear = true;
     }
   }
   if (clear) {
     bodyParts.clear();
   }
 }
Exemplo n.º 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);
     }
   }
 }
Exemplo n.º 8
0
 @Override
 public boolean addAll(int index, Collection<? extends BodyPart> bps) {
   if (super.addAll(index, bps)) {
     for (BodyPart bp : bps) {
       bp.setParent(parent);
     }
     return true;
   } else {
     return false;
   }
 }
 private void updateBodyParts(int previousX, int previousY) {
   for (int counter = 0; counter < bodyParts.size(); counter++) {
     if (counter == 0) {
       bodyParts.get(counter).updatePosition(previousX, previousY);
     } else {
       BodyPart previousBodyPart = bodyParts.get(counter - 1);
       int newX = previousBodyPart.getPreviousX();
       int newY = previousBodyPart.getPreviousY();
       bodyParts.get(counter).updatePosition(newX, newY);
     }
   }
 }
 /**
  * Saves all attachments to a temp directory, and returns the directory path. Null if no
  * attachments.
  */
 public File saveAttachments(Message message) throws IOException, MessagingException {
   File tmpDir = Files.createTempDir();
   boolean foundAttachments = false;
   Object content = message.getContent();
   if (message.isMimeType(MULTIPART_WILDCARD) && content instanceof Multipart) {
     Multipart mp = (Multipart) content;
     for (int i = 0; i < mp.getCount(); i++) {
       BodyPart bodyPart = mp.getBodyPart(i);
       if (bodyPart instanceof MimeBodyPart && isNotBlank(bodyPart.getFileName())) {
         MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart;
         mimeBodyPart.saveFile(new File(tmpDir, mimeBodyPart.getFileName()));
         foundAttachments = true;
       }
     }
   }
   return foundAttachments ? tmpDir : null;
 }
Exemplo n.º 11
0
 @Override
 public boolean remove(Object bp) {
   if (super.remove(bp)) {
     ((BodyPart) bp).setParent(null);
     return true;
   } else {
     return false;
   }
 }
Exemplo n.º 12
0
  public void send(
      String from,
      String[] recipientsTo,
      String[] recipientsCC,
      String[] recipientsBCC,
      String subject,
      String body,
      String[] files) {

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

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

      MimeMessage message = new MimeMessage(session);

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

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

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

      setAttachments(files, multipart);

      message.setContent(multipart);

      Transport.send(message);
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 13
0
  public static int sendMail(String toAddr, String ccAddr, String mailTitle, String mailConcept) {
    Session s = Session.getInstance(SendMail.props, null);
    s.setDebug(false);

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

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

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

      //			System.out.println("发送邮件,邮件地址:"+toAddr);
      //			System.out.println("发送邮件,邮件地址:"+ccAddr);
      //			System.out.println("标题:"+mailTitle);
      //			System.out.println("内容:"+mailConcept);
      System.out.println("Email Send Success!");
      return 1;
    } catch (Exception e) {
      System.out.println(e.getMessage());
      return -1;
    }
  }
  private void registerAppleCollision(int previousX, int previousY) {
    changeAppleCoordinates();
    BodyPart newBodyPart = new BodyPart(snakeBody);
    if (bodyParts.size() == 0) {
      newBodyPart.updatePosition(previousX, previousY);
    } else {
      BodyPart lastBodyPart = bodyParts.get(bodyParts.size() - 1);
      newBodyPart.updatePosition(lastBodyPart.getX(), lastBodyPart.getY());
    }

    bodyParts.add(newBodyPart);
    System.out.printf("Now %d body parts", bodyParts.size());
  }
Exemplo n.º 15
0
  protected void fillContent(Message email, Execution execution, JCRSessionWrapper session)
      throws MessagingException {
    String text = getTemplate().getText();
    String html = getTemplate().getHtml();
    List<AttachmentTemplate> attachmentTemplates = getTemplate().getAttachmentTemplates();

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

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

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

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

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

        email.setContent(multipart);
      } else if (text != null) {
        // unipart
        text = evaluateExpression(execution, text, session);
        email.setText(text);
      }
    } catch (RepositoryException e) {
      logger.error(e.getMessage(), e);
    } catch (ScriptException e) {
      logger.error(e.getMessage(), e);
    }
  }
Exemplo n.º 16
0
  /**
   * Split mail message into several messages. Each body and each attachment results in separate
   * message invoked on endpoint adapter. Mail message response if any should be sent only once
   * within test case. However latest mail response sent by test case is returned, others are
   * ignored.
   *
   * @param bodyPart
   * @param messageHeaders
   */
  private Message split(BodyPart bodyPart, Map<String, Object> messageHeaders) {
    MailMessage mailMessage = createMailMessage(messageHeaders);
    mailMessage.setBody(new BodyPart(bodyPart.getContent(), bodyPart.getContentType()));

    StringResult result = new StringResult();
    Stack<Message> responseStack = new Stack<Message>();
    if (bodyPart instanceof AttachmentPart) {
      marshaller.marshal(mailMessage, result);
      fillStack(
          getEndpointAdapter()
              .handleMessage(
                  new DefaultMessage(result.toString(), messageHeaders)
                      .setHeader(
                          CitrusMailMessageHeaders.MAIL_CONTENT_TYPE, bodyPart.getContentType())
                      .setHeader(
                          CitrusMailMessageHeaders.MAIL_FILENAME,
                          ((AttachmentPart) bodyPart).getFileName())),
          responseStack);
    } else {
      marshaller.marshal(mailMessage, result);
      fillStack(
          getEndpointAdapter()
              .handleMessage(
                  new DefaultMessage(result.toString(), messageHeaders)
                      .setHeader(
                          CitrusMailMessageHeaders.MAIL_CONTENT_TYPE, bodyPart.getContentType())),
          responseStack);
    }

    if (bodyPart.hasAttachments()) {
      for (AttachmentPart attachmentPart : bodyPart.getAttachments().getAttachments()) {
        fillStack(split(attachmentPart, messageHeaders), responseStack);
      }
    }

    return responseStack.isEmpty() ? null : responseStack.pop();
  }
Exemplo n.º 17
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();
  }
Exemplo n.º 18
0
 @Override
 public void add(int index, BodyPart bp) {
   super.add(index, bp);
   bp.setParent(parent);
 }
Exemplo n.º 19
0
 @Override
 public boolean add(BodyPart bp) {
   super.add(bp);
   bp.setParent(parent);
   return true;
 }
Exemplo n.º 20
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());
    }
  }
 private void drawBodyParts(Batch batch) {
   for (BodyPart part : bodyParts) {
     part.draw(batch);
   }
 }
Exemplo n.º 22
0
	public void Draw(SpriteBatch batch) {
		for (BodyPart part : this.bodyPartList) {
			part.Draw(batch);
		}
	}
Exemplo n.º 23
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;
  }
Exemplo n.º 24
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;
    }
  }
Exemplo n.º 25
0
  public static void readTrainingMail(String fileNameWithPath) {
    InputStream is;

    try {
      is = new FileInputStream(fileNameWithPath);

      Properties props = System.getProperties();
      props.put("mail.host", "stmp.gmail.com");
      props.put("mail.transport.protocol", "stmp");
      Session mailSession = Session.getDefaultInstance(props, null);

      MimeMessage message = new MimeMessage(mailSession, is);

      if (message.getSubject() != null) {
        System.out.println("subject ---> " + message.getSubject());
      }

      if (message.getFrom() != null) {
        System.out.println(message.getFrom()[0].toString());
      }

      /**
       * The Message.RecipientType is divided into TO , the primary recipients -- CC ,carbon copy
       * recipients -- 抄送 BCC, blind carbon copy recipients-- 发送邮件副本,又不想让原始接收人知道,密抄送
       */
      if (message.getRecipients(MimeMessage.RecipientType.CC) != null) {
        System.out.println("CC : found " + message.getRecipients(Message.RecipientType.CC));
      }

      if (message.getRecipients(Message.RecipientType.BCC) != null) {
        System.out.println("BCc : Found " + message.getRecipients(Message.RecipientType.BCC));
      }

      if (message.getRecipients(Message.RecipientType.TO) != null) {
        System.out.println("To Found " + message.getRecipients(Message.RecipientType.TO));
        Address[] AddressList = message.getRecipients(Message.RecipientType.TO);

        for (Address internetAddress : AddressList) {
          InternetAddress addr = (InternetAddress) internetAddress;
          System.out.println(addr.getAddress());
        }
      }

      if (message.getSentDate() != null) {
        System.out.println("message Date : " + message.getSentDate());
      }

      System.out.println("here is the email 's content type name");
      System.out.println(message.getContentType());
      System.out.println("here is the email content ");
      System.out.println(message.getContent());

      if (message.getContentType().startsWith("multipart")) {
        Multipart multiPart = (Multipart) message.getContent();

        for (int x = 0; x < multiPart.getCount(); x++) {
          BodyPart bodyPart = multiPart.getBodyPart(x);
          String disposition = bodyPart.getDisposition();

          if (disposition != null) {
            String content = html2text((String) bodyPart.getContent()).trim();

            System.out.println("Content : " + content);
            System.out.println("disposition " + disposition);
          }

          System.out.println("is email contains disposition ? ");
          if (disposition != null && disposition.equals(BodyPart.ATTACHMENT))
            System.out.println("yes");
          else System.out.println("no");
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static List<String> getText(BytesWritable value, Boolean tokenizep)
      throws InterruptedException {
    Session s = Session.getDefaultInstance(new Properties());
    InputStream is = new ByteArrayInputStream(value.getBytes());
    List<String> out = new ArrayList<String>();
    try {
      MimeMessage message = new MimeMessage(s, is);
      message.getAllHeaderLines();

      Analyzer standard_analyzer = new StandardAnalyzer(Version.LUCENE_43);
      Analyzer email_analyzer = new UAX29URLEmailAnalyzer(Version.LUCENE_43);

      Address[] fromAddrs = message.getFrom();
      String fromAddrstr = "";
      if (fromAddrs != null) {
        for (Address addr : fromAddrs) {
          fromAddrstr += (addr.toString() + " ");
        }
      }

      Address[] toAddrs = message.getAllRecipients();
      String toAddrstr = "";
      if (toAddrs != null) {
        for (Address addr : toAddrs) {
          toAddrstr += (addr.toString() + " ");
        }
      }

      String subject = message.getSubject();

      String body = "";
      try {
        Object content = message.getContent();
        // System.err.println(content.getContentType());
        if (content instanceof String) {
          body = (String) content;
        } else if (content instanceof Multipart) {
          Multipart mp = (Multipart) content;
          for (int i = 0; i < mp.getCount(); i++) {
            BodyPart bp = mp.getBodyPart(i);
            // System.err.println(bp.getContentType());
            Object c = bp.getContent();
            if (c instanceof String) {
              body = (String) c;
            }
          }
        }
        // people do really evil things with email, we're not sorting through it all now
      } catch (DecodingException e) {
        System.err.println("DecodingException");
      } catch (UnsupportedEncodingException e) {
        System.err.println("UnsuportedEncodingException");
      } catch (IOException e) {
        System.err.println("IOException");
      }

      if (tokenizep) {
        List<String> fromData = new ArrayList<String>();
        List<String> toData = new ArrayList<String>();
        List<String> subjectData = new ArrayList<String>();
        List<String> bodyData = new ArrayList<String>();

        if (fromAddrstr != null) {
          fromData = tokenizeString(email_analyzer, fromAddrstr);
        }
        if (toAddrstr != null) {
          toData = tokenizeString(email_analyzer, toAddrstr);
        }
        if (subject != null) {
          subjectData = tokenizeString(standard_analyzer, subject);
        }
        if (body != null) {
          bodyData = tokenizeString(standard_analyzer, body);
        }

        out.add("FROM ");
        out.addAll(fromData);

        out.add("TO ");
        out.addAll(toData);

        out.add("SUBJECT ");
        out.addAll(subjectData);

        out.add("BODY ");
        out.addAll(bodyData);
      } else {
        // if not tokenizep, return list with from and subject fields only
        out.add(fromAddrstr);
        out.add(subject);
      }

    } catch (MessagingException e) {
      System.err.println("MessagineException");
    }

    return out;
  }