public static void main(String[] args) {
    // Get the Properties and Create a default session
    Properties prop = System.getProperties();
    prop.setProperty("mail.server.com", "127.0.0.1");
    Session session = Session.getDefaultInstance(prop);

    try {
      // Set the mail headers
      MimeMessage msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress("*****@*****.**"));
      msg.setSubject("First Mail");

      // Create the mime body and attachments
      MimeBodyPart msgBody = new MimeBodyPart();
      msgBody.setContent("Hello World", "text/html");

      MimeBodyPart attFile = new MimeBodyPart();
      attFile.attachFile("RecvMail.java");

      Multipart partMsg = new MimeMultipart();
      partMsg.addBodyPart(msgBody);
      partMsg.addBodyPart(attFile);

      msg.setContent(partMsg);

      Transport.send(msg);

      System.out.println("Message Successfully sent...");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #2
0
  public void sendMailWithCalendar(
      String receivers, String subject, String body, String attachment) {
    log.info("Sending mail");
    try {
      Authenticator authenticator =
          new Authenticator(serverDetails.userName, serverDetails.password);
      Session session = Session.getDefaultInstance(properties, authenticator);
      MimeMessage message = new MimeMessage(session);

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

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

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

      messageBodyPart = new MimeBodyPart();
      messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
      messageBodyPart.setHeader("Content-ID", "calendar_message");
      messageBodyPart.setDataHandler(
          new DataHandler(
              new ByteArrayDataSource(Files.readAllBytes(Paths.get(attachment)), "text/calendar")));
      multipart.addBodyPart(messageBodyPart);
      message.setContent(multipart);
      Transport.send(message);
      log.info("Mail sent");
    } catch (Exception e) {
      log.severe("Could not send mail!" + e.getMessage());
    }
  }
Пример #3
0
  public static MimeMessage createTextMessageWithAttachments(
      Session session,
      String subject,
      String text,
      Address from,
      Address[] to,
      Attachment... attachments) {
    MimeMessage msg = createEmptyMimeMessage(session);
    try {
      msg.setSubject(subject, charset);
      msg.setFrom(from);
      msg.setRecipients(Message.RecipientType.TO, to);

      Multipart multipart = new MimeMultipart();

      MimeBodyPart textBodyPart = new MimeBodyPart();
      textBodyPart.setText(text, charset);
      multipart.addBodyPart(textBodyPart);

      if (attachments != null) {
        for (Attachment attachment : attachments) {
          appendAttachment(multipart, attachment);
        }
      }

      msg.setContent(multipart);
    } catch (MessagingException ex) {
      throw new RuntimeException(ex);
    }
    return msg;
  }
Пример #4
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);
  }
Пример #5
0
  /**
   * 对复杂邮件的解析
   *
   * @param multipart
   * @throws MessagingException
   * @throws IOException
   */
  public static void parseMultipart(Multipart multipart) throws MessagingException, IOException {
    int count = multipart.getCount();
    System.out.println("couont =  " + count);
    for (int idx = 0; idx < count; idx++) {
      BodyPart bodyPart = multipart.getBodyPart(idx);
      System.out.println(bodyPart.getContentType());
      if (bodyPart.isMimeType("text/plain")) {
        System.out.println("plain................." + bodyPart.getContent());
      } else if (bodyPart.isMimeType("text/html")) {
        System.out.println("html..................." + bodyPart.getContent());
      } else if (bodyPart.isMimeType("multipart/*")) {
        Multipart mpart = (Multipart) bodyPart.getContent();
        parseMultipart(mpart);

      } else if (bodyPart.isMimeType("application/octet-stream")) {
        String disposition = bodyPart.getDisposition();
        System.out.println(disposition);
        if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {
          String fileName = bodyPart.getFileName();
          InputStream is = bodyPart.getInputStream();
          copy(is, new FileOutputStream("D:\\" + fileName));
        }
      }
    }
  }
Пример #6
0
  public static String getText(Part part) {

    try {
      ContentType contentType = new ContentType(part.getContentType());
      System.err.println(
          "contentType: "
              + part.getContentType()
              + ", class: "
              + part.getContent().getClass().getName());

      if (part.isMimeType("text/*")) {
        String charset = contentType.getParameter("charset");
        System.err.println("Charset: " + charset);

        return (String) part.getContent();

      } else if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
          String text = getText(mp.getBodyPart(i));

          if (text != null) {
            return text;
          }
        }
      }
      return null;
    } catch (ParseException e) {
      throw new RuntimeException(e);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Пример #7
0
  private MimeMessage getMessage(Email email, Session session)
      throws AddressException, MessagingException {
    MimeMessage result = new MimeMessage(session);

    result.setFrom(new InternetAddress(email.getFrom()));
    result.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email.getTo()));
    result.setSubject(email.getSubject());

    if (email.getAttachment() != null) {
      // message body part
      MimeBodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(email.getMsg());

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

      MimeBodyPart attachmentPart = new MimeBodyPart();
      DataSource attachmentSource =
          new ByteArrayDataSource(
              email.getAttachment().getContent(), email.getAttachment().getAttachmentType());
      attachmentPart.setDataHandler(new DataHandler(attachmentSource));
      attachmentPart.setFileName(email.getAttachment().getFileName());

      multipart.addBodyPart(attachmentPart);

      result.setContent(multipart);
    } else {
      result.setContent(email.getMsg(), "text/plain");
    }

    return result;
  }
Пример #8
0
  /**
   * Extracts the content of a MimeMessage recursively.
   *
   * @param parent the parent multi-part
   * @param part the current MimePart
   * @throws MessagingException parsing the MimeMessage failed
   * @throws IOException parsing the MimeMessage failed
   */
  protected void parse(final Multipart parent, final MimePart part)
      throws MessagingException, IOException {
    if (isMimeType(part, "text/plain")
        && plainContent == null
        && !MimePart.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
      plainContent = (String) part.getContent();
    } else {
      if (isMimeType(part, "text/html")
          && htmlContent == null
          && !MimePart.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
        htmlContent = (String) part.getContent();
      } else {
        if (isMimeType(part, "multipart/*")) {
          this.isMultiPart = true;
          final Multipart mp = (Multipart) part.getContent();
          final int count = mp.getCount();

          // iterate over all MimeBodyPart

          for (int i = 0; i < count; i++) {
            parse(mp, (MimeBodyPart) mp.getBodyPart(i));
          }
        } else {
          final String cid = stripContentId(part.getContentID());
          final DataSource ds = createDataSource(parent, part);
          if (cid != null) {
            this.cidMap.put(cid, ds);
          }
          this.attachmentList.add(ds);
        }
      }
    }
  }
Пример #9
0
  // -- Private methods
  private MimeMessage createMimeMessage(
      MailController controller, Session session, OptionService os) throws MessagingException {
    MimeMessage msg = new MimeMessage(session);
    setSender(msg, os);
    setReplyTo(controller, msg);
    setFrom(controller, msg, os);
    addRecipients(controller, msg);
    setSubject(controller, msg);

    Multipart content = new MimeMultipart();
    msg.setContent(content);

    /* Text */
    String body = controller.getBody();
    if (!StringUtil.isEmpty(body)) {
      MimeBodyPart part = new MimeBodyPart();
      part.setContent(body, controller.getContentType());
      content.addBodyPart(part);
    }

    /* Attachments */
    List<File> attachments = controller.getAttachments();
    if (!attachments.isEmpty()) {
      for (File attachment : attachments) {
        MimeBodyPart part = new MimeBodyPart();
        DataSource source = new FileDataSource(attachment);
        part.setDataHandler(new DataHandler(source));
        part.setFileName(attachment.getName());
        content.addBodyPart(part);
      }
    }

    return msg;
  }
Пример #10
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());
    }
  }
Пример #11
0
  /**
   * 构建邮件的正文和附件
   *
   * @param msgContent
   * @param attachedFileList
   * @return
   * @throws javax.mail.MessagingException
   * @throws java.io.UnsupportedEncodingException
   */
  public static Multipart buildMimeMultipart(String msgContent, Vector<String> attachedFileList)
      throws MessagingException, UnsupportedEncodingException {
    Multipart mPart = new MimeMultipart(); // 多部分实现

    // 邮件正文
    MimeBodyPart mBodyContent = new MimeBodyPart(); // MIME邮件段体
    if (msgContent != null) {
      mBodyContent.setContent(msgContent, messageContentMimeType);
    } else {
      mBodyContent.setContent("", messageContentMimeType);
    }
    mPart.addBodyPart(mBodyContent);

    // 附件
    String file;
    String fileName;
    if (attachedFileList != null) {
      for (Enumeration<String> fileList = attachedFileList.elements();
          fileList.hasMoreElements(); ) {
        file = fileList.nextElement();
        fileName = file.substring(file.lastIndexOf("/") + 1);
        MimeBodyPart mBodyPart = new MimeBodyPart();
        // 远程资源
        // URLDataSource uds=new
        // URLDataSource(http://www.iteye.com/logo.gif);
        FileDataSource fds = new FileDataSource(file);
        mBodyPart.setDataHandler(new DataHandler(fds));
        // mBodyPart.setFileName(fileName);
        mBodyPart.setFileName(MimeUtility.encodeWord(fileName)); // 解决中文附件名问题
        mPart.addBodyPart(mBodyPart);
      }
    }

    return mPart;
  }
Пример #12
0
  private Message gerarMensagem(String emissor, String destino, String assunto) {
    Message mensagem = new MimeMessage(_sessao);
    try {
      mensagem.setFrom(new InternetAddress(emissor));
      mensagem.setRecipient(Message.RecipientType.TO, new InternetAddress(destino));
      mensagem.setSubject(assunto);

      if (_existemAnexos) {
        MimeBodyPart conteudo = new MimeBodyPart();
        if (_tipoMensagem.equals(Conteudo.HTML)) {
          conteudo.setContent(_texto, TipoConteudo.HTML);
        } else {
          conteudo.setContent(_texto, TipoConteudo.TEXTO);
        }
        Multipart divisoesConteudo = new MimeMultipart();
        divisoesConteudo.addBodyPart(conteudo);
        inserirAnexosArquivo(divisoesConteudo);
        inserirAnexosConteudo(divisoesConteudo);
        mensagem.setContent(divisoesConteudo);
      } else {
        if (_tipoMensagem.equals(Conteudo.HTML)) {
          mensagem.setContent(_texto, TipoConteudo.HTML);
        } else {
          mensagem.setContent(_texto, TipoConteudo.TEXTO);
        }
      }

    } catch (MessagingException ex) {
      Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
      mensagem = null;
    }

    return mensagem;
  }
Пример #13
0
  public static void send(
      String nomContact,
      Integer numFacture,
      Double montantCommande,
      Integer nbLots,
      String typeEnvoi,
      String adresseContact)
      throws Exception {

    Properties props = System.getProperties();
    props.put("mail.smtps.host", "smtp.orange.fr");
    props.put("mail.smtps.auth", "true");

    Session session = Session.getInstance(props, null);
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress("*****@*****.**"));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(adresseContact, false));

    String corpsMessage =
        "Bonjour "
            + nomContact
            + "\n\n"
            + "votre commande n°"
            + numFacture
            + " d'un montant de "
            + montantCommande
            + "€ TTC vient d'être traitée.\n\n"
            + typeEnvoi
            + " \n\n"
            + "L'équipe du ciné cap vert vous remercie de votre confiance.\n\n\n\n"
            + " P.S.: Retrouvez en pièce jointe le mode d'emploi des chèques cinéma sur notre interface de réservation en ligne";

    msg.setSubject("Votre commande de " + nbLots + " lots de chèques cinéma vient d'être traitée.");
    msg.setHeader("X-Mailer", "Test En-tete");
    msg.setSentDate(new Date());

    // create and fill the first message part
    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(corpsMessage);

    // create the second message part
    MimeBodyPart mbp2 = new MimeBodyPart();

    // attach the file to the message
    mbp2.attachFile("ccvad.png");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);
    mp.addBodyPart(mbp2);

    // add the Multipart to the message
    msg.setContent(mp);

    SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
    t.connect("smtp.orange.fr", "*****@*****.**", "popcorn21800");
    t.sendMessage(msg, msg.getAllRecipients());
    System.out.println("Réponse: " + t.getLastServerResponse());
    t.close();
  }
 private void addAttachments(String msgText, MimeMessage msg) throws MessagingException {
   Enumeration docs = as.getRelatedTopics(getID(), SEMANTIC_EMAIL_ATTACHMENT, 2).elements();
   Multipart mp = null;
   while (docs.hasMoreElements()) {
     BaseTopic doc = (BaseTopic) docs.nextElement();
     if (doc.getType().equals(TOPICTYPE_DOCUMENT)) {
       String sFileName = getProperty(doc, PROPERTY_FILE);
       String sFile = FileServer.repositoryPath(FILE_DOCUMENT) + sFileName;
       MimeBodyPart mbp = new MimeBodyPart();
       FileDataSource ds = new FileDataSource(sFile);
       DataHandler dh = new DataHandler(ds);
       mbp.setDataHandler(dh);
       String sFileDoc = doc.getName();
       if ((sFileDoc != null) && !sFileDoc.equals("")) {
         mbp.setFileName(sFileDoc);
       } else {
         mbp.setFileName(sFileName);
       }
       if (mp == null) {
         mp = new MimeMultipart();
         MimeBodyPart mbpText = new MimeBodyPart();
         mbpText.setText(msgText, "UTF-8");
         mp.addBodyPart(mbpText);
       }
       mp.addBodyPart(mbp);
     }
   }
   // multi part or not
   if (mp != null) {
     msg.setContent(mp);
   } else {
     msg.setText(msgText, "UTF-8");
   }
 }
Пример #15
0
  public synchronized void sendImage(
      String subject, String body, String sender, String recipients, File attachment)
      throws Exception {

    try {
      MimeMessage message = new MimeMessage(session);
      message.setSender(new InternetAddress(sender));
      message.setSubject(subject);

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

      MimeBodyPart mbp2 = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(attachment);
      mbp2.setDataHandler(new DataHandler(fds));
      mbp2.setFileName(fds.getName());

      Multipart mp = new MimeMultipart();
      mp.addBodyPart(mbp1);
      mp.addBodyPart(mbp2);

      message.setContent(mp);

      if (recipients.indexOf(',') > 0)
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
      else message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
      Transport.send(message);
    } catch (Exception e) {
      Log.e("GmalSender", "Exception", e);
    }
  }
 /**
  * Helper method: builds a multipart email part.
  *
  * @param topLevel If part should be a Message.
  * @param parts Child parts to include.
  * @return Multipart part.
  * @throws MessagingException Won't.
  * @throws IOException Won't.
  */
 private Part makeMultipart(final boolean topLevel, final Part... parts)
     throws MessagingException, IOException {
   final Part bp =
       context.mock((topLevel ? Message.class : BodyPart.class), "BodyPart-" + (++uniqueIndex));
   final Multipart mp =
       new Multipart() {
         @Override
         public void writeTo(final OutputStream inOs) throws IOException, MessagingException {}
       };
   context.checking(
       new Expectations() {
         {
           allowing(bp).getDisposition();
           will(returnValue(null));
           allowing(bp).getContentType();
           will(returnValue("multipart/alternative;\r\nboundary=something"));
           allowing(bp).getContent();
           will(returnValue(mp));
         }
       });
   for (int i = 0; i < parts.length; i++) {
     mp.addBodyPart((BodyPart) parts[i]);
   }
   return bp;
 }
Пример #17
0
  public void setMessage(MimeMessage message) {
    if (message != null) {
      // serialize the message
      this.message = message;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      try {
        message.writeTo(baos);
        baos.flush();
        serializedBytes = baos.toByteArray();
        this.contentType = message.getContentType();

        // see if this is a multi-part message
        Object content = message.getContent();
        if (content instanceof Multipart) {
          Multipart mp = (Multipart) content;
          this.parts = mp.getCount();
        } else {
          this.parts = 0;
        }
      } catch (MessagingException e) {
        Debug.logError(e, module);
      } catch (IOException e) {
        Debug.logError(e, module);
      } finally {
        try {
          baos.close();
        } catch (IOException e) {
          Debug.logError(e, module);
        }
      }
    }
  }
Пример #18
0
  public void sendOTPToEmail(String to, String subject, String Username, String Password) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    switch (protocol) {
      case SMTPS:
        props.put("mail.smtp.ssl.enable", true);
        break;
      case TLS:
        props.put("mail.smtp.starttls.enable", true);
        break;
    }

    Authenticator authenticator = null;
    if (auth) {
      props.put("mail.smtp.auth", true);
      authenticator =
          new Authenticator() {
            private PasswordAuthentication pa = new PasswordAuthentication(username, password);

            @Override
            public PasswordAuthentication getPasswordAuthentication() {
              return pa;
            }
          };
    }

    Session session = Session.getInstance(props, authenticator);

    MimeMessage message = new MimeMessage(session);
    try {
      message.setFrom(new InternetAddress(from));
      InternetAddress[] address = {new InternetAddress(to)};
      message.setRecipients(Message.RecipientType.TO, address);
      message.setSubject(subject);
      message.setSentDate(new Date());
      /* message.setText(body); */
      Multipart multipart = new MimeMultipart("alternative");

      MimeBodyPart textPart = new MimeBodyPart();
      // If email client does not support html-------------------------
      String textContent = "Username: "******" Password:"******"<html><h1>QCollect "
              + "</h1><p><h3>Please Use the following OTP to login to your Account</h3></p>"
              + Password
              + "</p></html>";
      htmlPart.setContent(htmlContent, "text/html");
      multipart.addBodyPart(textPart);
      multipart.addBodyPart(htmlPart);
      message.setContent(multipart);
      Transport.send(message);
    } catch (MessagingException ex) {
      ex.printStackTrace();
    }
  }
Пример #19
0
 private void loadMail(Part p) throws Exception {
   Object content = p.getContent();
   if (content instanceof Multipart) {
     Multipart mp = (Multipart) content;
     int cnt = mp.getCount();
     for (int i = 0; i < cnt; i++) loadMail(mp.getBodyPart(i));
   }
 }
Пример #20
0
 public String parseMultipart(BodyPart msg) throws MessagingException, IOException {
   if (msg.isMimeType("text/*")) {
     return msg.getContent().toString();
   } else {
     Multipart mpart = (Multipart) msg.getContent();
     return parseMultipart(mpart.getBodyPart(0));
   }
 }
Пример #21
0
    private String getRawText(Object o) throws MessagingException, IOException {

      String s = null;

      if (o instanceof Multipart) {
        Multipart multi = (Multipart) o;
        for (int i = 0; i < multi.getCount(); i++) {
          s = getRawText(multi.getBodyPart(i));
          if (s != null) {
            if (s.length() > 0) {
              break;
            }
          }
        }
      } else if (o instanceof BodyPart) {
        BodyPart aBodyContent = (BodyPart) o;
        StringTokenizer aTypeTokenizer = new StringTokenizer(aBodyContent.getContentType(), "/");
        String abstractType = aTypeTokenizer.nextToken();
        if (abstractType.compareToIgnoreCase("MESSAGE") == 0) {
          Message inlineMessage = (Message) aBodyContent.getContent();
          s = getRawText(inlineMessage.getContent());
        }
        if (abstractType.compareToIgnoreCase("APPLICATION") == 0) {
          s = "Attached File: " + aBodyContent.getFileName();
        }
        if (abstractType.compareToIgnoreCase("TEXT") == 0) {
          try {
            Object oS = aBodyContent.getContent();
            if (oS instanceof String) {
              s = (String) oS;
            } else {
              throw (new MessagingException("Unkown MIME Type (?): " + oS.getClass()));
            }
          } catch (Exception e) {
            throw (new MessagingException(
                "Unable to read message contents (" + e.getMessage() + ")"));
          }
        }
        if (abstractType.compareToIgnoreCase("MULTIPART") == 0) {
          s = getRawText(aBodyContent.getContent());
        }
      }

      if (o instanceof String) {
        s = (String) o;
      }

      //          else {
      //              if (m.isMimeType("text/html")) {
      //                  s = m.getContent().toString();
      //              }
      //              if (m.isMimeType("text/plain")) {
      //                  s = m.getContent().toString();
      //              }
      //          }

      return s;
    }
Пример #22
0
  private void _Memo(
      String sender, String personal, List<String> recipients, String subj, String body) {
    if (Environment.mailEnable) {
      Properties props = new Properties();
      props.put("mail.smtp.host", smtpServer);
      Session ses;
      if (smtpAuth) {
        props.put("mail.smtp.auth", smtpAuth);
        props.put("mail.smtp.port", smtpPort);
        if ("465".equals(smtpPort)) {
          props.put("mail.smtp.ssl.enable", "true");
        }
        Authenticator auth = new SMTPAuthenticator();
        ses = Session.getInstance(props, auth);
      } else {
        ses = Session.getInstance(props, null);
      }

      msg = new MimeMessage(ses);
      hasRecipients = false;

      try {
        if (personal == null) {
          msg.setFrom(new InternetAddress(sender));
        } else {
          msg.setFrom(new InternetAddress(sender, personal));
        }

        for (String recipient : recipients) {
          try {
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            hasRecipients = true;
          } catch (AddressException ae) {
            Server.logger.errorLogEntry("incorrect e-mail \"" + recipient + "\"");
            continue;
          }
        }

        if (hasRecipients) {
          msg.setSubject(subj, "utf-8");
          Multipart mp = new MimeMultipart();
          BodyPart htmlPart = new MimeBodyPart();
          htmlPart.setContent(body, "text/html; charset=utf-8");
          mp.addBodyPart(htmlPart);
          msg.setContent(mp);
          isValid = true;
        } else {
          Server.logger.errorLogEntry(
              "unable to send the message. List of recipients is empty or consist is incorrect data");
        }
      } catch (MessagingException e) {
        Server.logger.errorLogEntry(e);
      } catch (UnsupportedEncodingException e) {
        Server.logger.errorLogEntry(e);
      }
    }
  }
Пример #23
0
  /** Method for checking if the message has attachments. */
  public boolean hasAttachments() throws java.io.IOException, MessagingException {
    boolean hasAttachments = false;
    if (message.isMimeType("multipart/*")) {
      Multipart mp = (Multipart) message.getContent();
      if (mp.getCount() > 1) hasAttachments = true;
    }

    return hasAttachments;
  }
Пример #24
0
  public void testAttachments() throws Exception {
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "localhost");
    props.setProperty("mail.smtp.port", SMTP_PORT + "");
    Session session = Session.getInstance(props);

    MimeMessage baseMsg = new MimeMessage(session);
    MimeBodyPart bp1 = new MimeBodyPart();
    bp1.setHeader("Content-Type", "text/plain");
    bp1.setContent("Hello World!!!", "text/plain; charset=\"ISO-8859-1\"");

    // Attach the file
    MimeBodyPart bp2 = new MimeBodyPart();
    FileDataSource fileAttachment = new FileDataSource(BIGFILE_PATH);
    DataHandler dh = new DataHandler(fileAttachment);
    bp2.setDataHandler(dh);
    bp2.setFileName(fileAttachment.getName());

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(bp1);
    multipart.addBodyPart(bp2);

    baseMsg.setFrom(new InternetAddress("Ted <*****@*****.**>"));
    baseMsg.setRecipient(Message.RecipientType.TO, new InternetAddress("*****@*****.**"));
    baseMsg.setSubject("Test Big attached file message");
    baseMsg.setContent(multipart);
    baseMsg.saveChanges();

    LOG.debug("Send started");
    Transport t = new SMTPTransport(session, new URLName("smtp://*****:*****@example.org")});
    t.close();
    started = System.currentTimeMillis() - started;
    LOG.info("Elapsed ms = " + started);

    WiserMessage msg = server.getMessages().get(0);

    assertEquals(1, server.getMessages().size());
    assertEquals("*****@*****.**", msg.getEnvelopeReceiver());

    File compareFile = File.createTempFile("attached", ".tmp");
    LOG.debug("Writing received attachment ...");

    FileOutputStream fos = new FileOutputStream(compareFile);
    ((MimeMultipart) msg.getMimeMessage().getContent())
        .getBodyPart(1)
        .getDataHandler()
        .writeTo(fos);
    fos.close();
    LOG.debug("Checking integrity ...");
    assertTrue(checkIntegrity(new File(BIGFILE_PATH), compareFile));
    LOG.debug("Checking integrity DONE");
    compareFile.delete();
    msg.dispose();
  }
Пример #25
0
 private void extractFiles() throws IOException, MessagingException {
   if (message.getContent() instanceof Multipart) {
     Multipart mp = (Multipart) message.getContent();
     for (int i = 0; i < mp.getCount(); i++) {
       BodyPart bp = mp.getBodyPart(i);
       getMultipart(bp, bp.getContent());
     }
   }
 }
Пример #26
0
  public void send() {

    Properties props = new Properties();

    props.setProperty("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    Session mailSession = Session.getDefaultInstance(props);
    // mailSession.setDebug(true);
    Transport transport;
    try {
      transport = mailSession.getTransport();

      MimeMessage message = new MimeMessage(mailSession);
      message.setFrom(new InternetAddress(userName));
      message.setSubject(subject);

      message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

      if (!cc.equals("")) {
        message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
      }
      if (!bcc.equals("")) {
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));
      }

      // create the message part
      MimeBodyPart messageBodyPart = new MimeBodyPart();

      // fill message
      messageBodyPart.setText(content);

      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);
      if (fList != null) {
        Iterator<File> i = fList.iterator();
        // part two is attachment
        while (i.hasNext()) {
          File file = (File) i.next();
          messageBodyPart = new MimeBodyPart();
          DataSource source = new FileDataSource(file);
          messageBodyPart.setDataHandler(new DataHandler(source));
          messageBodyPart.setFileName(file.getName());
          multipart.addBodyPart(messageBodyPart);
        }
      }
      // Put parts in message
      message.setContent(multipart);

      Transport.send(message);

      transport.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #27
0
    /**
     * Handel multipart messages recursive until we find the first text/html message. Or text/plain
     * if html is not available.
     *
     * @param multipart the multipart portion
     * @param message the message
     * @param builder the email value builder
     * @throws MessagingException
     * @throws IOException
     */
    private void handleMultipart(
        Multipart multipart, Message message, ValueBuilder<EmailValue> builder)
        throws MessagingException, IOException {
      String body = "";

      String contentType = cleanContentType(multipart.getContentType());

      for (int i = 0, n = multipart.getCount(); i < n; i++) {
        BodyPart part = multipart.getBodyPart(i);

        String disposition = part.getDisposition();

        if ((disposition != null)
            && ((disposition.equalsIgnoreCase(Part.ATTACHMENT)
                || (disposition.equalsIgnoreCase(Part.INLINE))))) {
          builder
              .prototype()
              .attachments()
              .get()
              .add(createAttachedFileValue(message.getSentDate(), part));

        } else {
          if (part.isMimeType(Translator.PLAIN)) {
            // if contents is multipart mixed concatenate text plain parts
            if ("multipart/mixed".equalsIgnoreCase(contentType)) {
              body += (String) part.getContent() + "\n\r";
            } else {
              body = (String) part.getContent();
            }
            builder.prototype().content().set(body);
            builder.prototype().contentType().set(Translator.PLAIN);

          } else if (part.isMimeType(Translator.HTML)) {
            body = (String) part.getContent();
            builder.prototype().contentHtml().set(body);
            builder.prototype().contentType().set(Translator.HTML);

          } else if (part.isMimeType("image/*")) {
            builder
                .prototype()
                .attachments()
                .get()
                .add(createAttachedFileValue(message.getSentDate(), part));

          } else if (part.getContent() instanceof Multipart) {
            handleMultipart((Multipart) part.getContent(), message, builder);
          }
        }
      }
      // if contentHtml is not empty set the content type to text/html
      if (!Strings.empty(builder.prototype().contentHtml().get())) {
        builder.prototype().content().set(builder.prototype().contentHtml().get());
        builder.prototype().contentType().set(Translator.HTML);
      }
    }
Пример #28
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);
    }*/
  }
Пример #29
0
  /** Since Openbravo 3.0MP9 only {@link #sendEmail()} is used for the full email sending cycle */
  @Deprecated
  public void sendSimpleEmail(
      Session session,
      String from,
      String to,
      String bcc,
      String subject,
      String body,
      String attachmentFileLocations)
      throws PocException {
    try {
      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));

      message.setRecipients(Message.RecipientType.TO, getAddressesFrom(to.split(",")));

      if (bcc != null)
        message.setRecipients(Message.RecipientType.BCC, getAddressesFrom(bcc.split(",")));

      message.setSubject(subject);

      // Content consists of 2 parts, the message body and the attachment
      // We therefore use a multipart message
      Multipart multipart = new MimeMultipart();

      // Create the message part
      MimeBodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(body);
      multipart.addBodyPart(messageBodyPart);

      // Create the attachment parts
      if (attachmentFileLocations != null) {
        String attachments[] = attachmentFileLocations.split(",");

        for (String attachment : attachments) {
          messageBodyPart = new MimeBodyPart();
          DataSource source = new FileDataSource(attachment);
          messageBodyPart.setDataHandler(new DataHandler(source));
          messageBodyPart.setFileName(attachment.substring(attachment.lastIndexOf("/") + 1));
          multipart.addBodyPart(messageBodyPart);
        }
      }

      message.setContent(multipart);

      // Send the email
      Transport.send(message);
    } catch (AddressException exception) {
      throw new PocException(exception);
    } catch (MessagingException exception) {
      throw new PocException(exception);
    }
  }
Пример #30
0
 /**
  * 分析邮件
  *
  * @param content
  */
 public static void parseMailContent(Object content) {
   try {
     if (content instanceof Multipart) {
       Multipart mPart = (MimeMultipart) content;
       for (int i = 0; i < mPart.getCount(); i++) {
         extractPart((MimeBodyPart) mPart.getBodyPart(i));
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }