Ejemplo n.º 1
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);
 }
  /*
   * Writes/Sends an Email
   */
  public void writeConfirmationEmail(
      String firstName, String lastName, String username, String password, String email) {
    String to = email;
    String from = "*****@*****.**";
    String host = "smtp.ilstu.edu";
    Properties properties = System.getProperties();

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

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

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

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

      Transport.send(message);

      System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
  }
Ejemplo n.º 3
0
  protected void addBodyPartHeaders(BodyPart part, String name, MuleMessage message) {
    Map headers =
        (Map) message.getProperty(name + MailMessageAdapter.ATTACHMENT_HEADERS_PROPERTY_POSTFIX);

    if (null != headers) {
      for (Iterator it = headers.keySet().iterator(); it.hasNext(); ) {
        try {
          String key = (String) it.next();
          part.setHeader(key, (String) headers.get(key));
        } catch (MessagingException me) {
          logger.error("Failed to set bodypart header", me);
        }
      }
    }
  }
Ejemplo n.º 4
0
  private Message createMessage(Session session, User user2) throws Exception {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(email));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
    message.setSubject("中工精品课程修改密码邮件");

    // 创建MimeBodyPart封装正文
    MimeBodyPart text = new MimeBodyPart();

    Date time = new Date();

    String con =
        "尊敬的"
            + user.getNickname()
            + "您好!</br>下面是重置密码的链接,<font color='red'>一个小时之内请点击进入重置密码,否则失效</font>,我会等着你的哦!"
            + "<div><a href='http://localhost:8080/ExcellentCourse/servlet/ResetPwdServlet?uid="
            + user.getId()
            + "&time="
            + time.getTime()
            + "'>重置密码   uid="
            + user.getId()
            + "  time="
            + time.getTime()
            + " </a></div>"
            + "<img src='cid:logo'/>";
    text.setContent(con, "text/html;charset=UTF-8");

    // chuangjian image
    // 创建图片
    MimeMultipart mm = new MimeMultipart();

    BodyPart image1 = createInlineImagePart(context.getRealPath("images/email/beauty.jpg"));
    image1.setHeader("Content-ID", "logo");
    mm.addBodyPart(text);
    mm.addBodyPart(image1);
    mm.setSubType("related");

    message.setContent(mm);
    message.saveChanges();
    // message.writeTo(new FileOutputStream("c:\\1.eml"));
    return message;
  }
 @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);
   }
 }
Ejemplo n.º 6
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();
    }
  }