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();
    }
  }
Exemplo n.º 2
3
  public void sendSimpleEmailAuthenticated(
      String SMTPHost,
      String userName,
      String password,
      String subject,
      String body,
      String toAddress,
      String fromAddress)
      throws MessagingException {
    SMTP_AUTH_USER = userName;
    SMTP_AUTH_PWD = password;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTPHost);
    props.put("mail.smtp.auth", "true");

    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    MimeMessage message = new MimeMessage(session);

    message.setSubject(subject);
    message.setContent(body, "text/plain");

    message.setFrom(new InternetAddress(fromAddress));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));

    Transport.send(message);
  }
Exemplo n.º 3
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;
  }
Exemplo n.º 4
0
  public static MimeMessage createMessage(
      Session session,
      String subject,
      String html,
      String text,
      Address from,
      Address[] to,
      Attachment... attachments) {

    if (text == null) text = Html.convertHtmlToText(html);

    MimeMessage msg = createEmptyMimeMessage(session);
    try {
      msg.setSubject(subject, charset);
      msg.setFrom(from);
      msg.setRecipients(Message.RecipientType.TO, to);

      if ((attachments == null || attachments.length == 0)) {
        // no attachments

        if (Str.isBlank(html)) {
          // no html
          msg.setText(text, charset);
          return msg;
        }

        msg.setContent(createMultipartAlternative(text, html));
        return msg;
      }

      MimeMultipart multipartMixed = new MimeMultipart("mixed");

      if (Str.isBlank(html)) {
        // no html
        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(text, charset);
        multipartMixed.addBodyPart(textBodyPart);
      } else {
        // html
        MimeBodyPart wrapAlternative = new MimeBodyPart();
        wrapAlternative.setContent(createMultipartAlternative(text, html));
        multipartMixed.addBodyPart(wrapAlternative);
      }

      for (Attachment attachment : attachments) {
        appendAttachment(multipartMixed, attachment);
      }

      msg.setContent(multipartMixed);
      return msg;

    } catch (MessagingException ex) {
      throw new RuntimeException(ex);
    }
  }
Exemplo n.º 5
0
  /** 根据传入的 Seesion 对象创建混合型的 MIME消息 */
  public MimeMessage createMessage(Session session) throws Exception {
    String from = "*****@*****.**";
    String to = "*****@*****.**";
    String subject = "创建内含附件、图文并茂的邮件!";
    String body =
        "<h4>内含附件、图文并茂的邮件测试!!!</h4> </br>"
            + "<a href = http://haolloyin.blog.51cto.com/> 蚂蚁</a></br>"
            + "<img src = \"cid:logo_jpg\"></a>";

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject(subject);

    // 创建邮件的各个 MimeBodyPart 部分
    MimeBodyPart attachment01 = createAttachment("F:\\java\\Snake.java");
    MimeBodyPart attachment02 = createAttachment("F:\\java\\meng.mp3");
    MimeBodyPart content = createContent(body, "F:\\java\\logo.jpg");

    // 将邮件中各个部分组合到一个"mixed"型的 MimeMultipart 对象
    MimeMultipart allPart = new MimeMultipart("mixed");
    allPart.addBodyPart(attachment01);
    allPart.addBodyPart(attachment02);
    allPart.addBodyPart(content);

    // 将上面混合型的 MimeMultipart 对象作为邮件内容并保存
    msg.setContent(allPart);
    msg.saveChanges();
    return msg;
  }
Exemplo n.º 6
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());
    }
  }
Exemplo n.º 7
0
  public static void sendMail(String recipient, String subject, String body)
      throws MessagingException {

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

    MimeMessage message = new MimeMessage(session);

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

    message.setSubject(subject);

    message.setContent(body, "text/html; charset=utf-8");

    logger.debug("send email to " + recipient);

    Transport.send(message);
  }
Exemplo n.º 8
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;
  }
  @Override
  public void run() {
    LOGGER.info("***********Inside send e-Mail Thread************");
    LOGGER.info("Sending email to:: E-mail Address::" + emailModel.getToaddess());
    Session mailSession = createSmtpSession();
    mailSession.setDebug(true);
    List<String> toAddresses = new ArrayList<String>();

    try {
      Transport transport = mailSession.getTransport();
      MimeMessage message = new MimeMessage(mailSession);

      message.setSubject(emailModel.getSubject());
      message.setFrom(new InternetAddress(emailModel.getFromAddress()));
      message.setContent(emailModel.getContent(), "text/html");

      toAddresses.add(emailModel.getToaddess());
      transport.connect();
      Iterator<String> itr = toAddresses.iterator();
      while (itr.hasNext()) {
        String toAddress = (String) itr.next();
        message.addRecipients(Message.RecipientType.TO, toAddress);
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
      }
      LOGGER.info("Successfully sent email to:: E-mail Address::" + emailModel.getToaddess());
    } catch (MessagingException e) {
      LOGGER.error("Cannot Send email", e);
    }
  }
Exemplo n.º 10
0
  public static void sendEmail(
      InternetAddress from, InternetAddress to, String content, String requester)
      throws MessagingException, UnsupportedEncodingException {

    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("MN Traffic Generation is used by " + requester);
    message.setContent(content, "text/plain");

    message.addRecipient(Message.RecipientType.TO, to);

    InternetAddress[] replyto = new InternetAddress[1];
    replyto[0] = from;

    message.setFrom(from);
    message.setReplyTo(replyto);
    message.setSender(from);

    transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));

    transport.close();
  }
Exemplo n.º 11
0
  /** 发�?邮件 */
  public boolean sendOut() {
    try {
      mimeMsg.setContent(mp);
      mimeMsg.saveChanges();
      System.out.println("正在发�?邮件....");

      Session mailSession = Session.getInstance(props, null);
      Transport transport = mailSession.getTransport("smtp");
      transport.connect((String) props.get("mail.smtp.host"), username, password);
      transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
      //          如果抄�?人为null  不添加抄送人
      if (mimeMsg.getRecipients(Message.RecipientType.CC) != null)
        transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
      // transport.send(mimeMsg);

      System.out.println("发送邮件成功");
      transport.close();

      return true;
    } catch (Exception e) {
      System.err.println("邮件发送失败" + e);
      e.printStackTrace();
      return false;
    }
  }
Exemplo n.º 12
0
  public boolean send() {
    try {
      Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
      Properties props = new Properties();
      props.setProperty("mail.transport.protocol", "smtp");
      props.setProperty("mail.host", "smtp.gmail.com");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");
      props.put("mail.debug", "true");
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.socketFactory.fallback", "false");
      Session session = Session.getDefaultInstance(props, new GJMailAuthenticator());
      session.setDebug(true);
      Transport transport = session.getTransport();
      InternetAddress addressFrom = new InternetAddress("*****@*****.**");
      MimeMessage message = new MimeMessage(session);
      message.setSender(addressFrom);
      message.setSubject(subject);
      message.setContent(text, "text/html");
      InternetAddress addressTo = new InternetAddress(to);
      message.setRecipient(Message.RecipientType.TO, addressTo);
      transport.connect();
      Transport.send(message);
      transport.close();
      System.out.println("DONE");

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

    return true;
  }
Exemplo n.º 13
0
  public void test() throws Exception {

    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");
    props.put("mail.smtps.quitwait", "false");
    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(true);

    Transport transport = mailSession.getTransport();
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(username.getText()));
    message.setSubject(subject.getText());

    String s = msgfield.getText();
    message.setContent(s, "text/plain");
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailID.getText()));
    System.out.println("8i m here ");
    try {
      transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, username.getText(), password.getText());
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, "invalid username or password");
    }
    System.out.println("8i m here also yaar");
    // transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
    transport.sendMessage(message123, message123.getAllRecipients());
    transport.close();
    System.out.println(s);
  }
Exemplo n.º 14
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());
    }
  }
Exemplo n.º 15
0
  /**
   * Este método é responsável por enviar email.
   *
   * @param pServidorSMTP
   * @param pDe
   * @param pPara
   * @param pCopia
   * @param pBcc
   * @param pAssunto
   * @param pTexto
   * @return true se o email for enviado, false caso contrário.
   */
  public static boolean enviarEmail(
      final String pServidorSMTP,
      final String pDe,
      final String pPara,
      final String pCopia,
      final String pBcc,
      final String pAssunto,
      final String pTexto) {

    Properties mailPprops = new Properties();
    mailPprops.put("mail.smtp.host", pServidorSMTP);

    Session mailSession = Session.getDefaultInstance(mailPprops, null);

    try {
      // Mudança: Aplicação usa ";", componente usa ","
      String para = pPara.replaceAll(";", ",");

      // Criando a mensagem
      MimeMessage msg = new MimeMessage(mailSession);
      // Atribuir rementente
      msg.setFrom(new InternetAddress(pDe));
      // Atribuir destinatários
      InternetAddress[] endereco = null;
      // Para
      if ((para != null) && (!para.equals(""))) {
        endereco = InternetAddress.parse(para);
        msg.setRecipients(Message.RecipientType.TO, endereco);
      }
      // Cc
      if ((pCopia != null) && (!pCopia.equals(""))) {
        endereco = InternetAddress.parse(pCopia);
        msg.setRecipients(Message.RecipientType.CC, endereco);
      }
      // Bcc
      if ((pBcc != null) && (!pBcc.equals(""))) {
        endereco = InternetAddress.parse(pBcc);
        msg.setRecipients(Message.RecipientType.BCC, endereco);
      }

      // Atribuir assunto
      msg.setSubject(pAssunto);

      // Atribuir corpo do email (texto)
      if (pTexto != null) msg.setContent(pTexto, "text/html");

      msg.setSentDate(new Date());

      Transport.send(msg);

      msg = null;
      mailSession = null;
    } catch (MessagingException mex) {
      if (Constants.DEBUG) {
        mex.printStackTrace(System.out);
      }
      return false;
    }
    return true;
  }
Exemplo n.º 16
0
  public void setMessageContent(
      MimeMessage message, String subject, String bodyText, String bodyHtml) {
    try {
      message.setSubject(subject);

      MimeBodyPart textPart = new MimeBodyPart();
      textPart.setText(bodyText.toString(), "UTF-8");

      MimeBodyPart htmlPart = new MimeBodyPart();
      htmlPart.setContent(bodyHtml.toString(), "text/html; charset=UTF-8");

      MimeMultipart multiPart = new MimeMultipart();
      // "alternative" means display only one or the other, "mixed" means both
      multiPart.setSubType("alternative");

      // I read something on the internet saying to put the text part first
      // so sucktastic mail clients see it first
      multiPart.addBodyPart(textPart);
      multiPart.addBodyPart(htmlPart);

      message.setContent(multiPart);
    } catch (MessagingException e) {
      throw new RuntimeException("failed to put together MIME message", e);
    }
  }
Exemplo n.º 17
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;
  }
Exemplo n.º 18
0
  /**
   * Generate a MimeMessage with the specified attributes
   *
   * @param destEmailAddr The destination email address
   * @param fromEmailAddr The sender email address
   * @param fromName The senders display name
   * @param emailSubject The subject
   * @param emailPlainText The message body (plaintext)
   * @return The MimeMessage object
   * @throws Exception
   */
  public static MimeMessage generateMail(
      String destEmailAddr,
      String destPersonalName,
      String fromEmailAddr,
      String fromName,
      String emailSubject,
      String emailPlainText)
      throws Exception {

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));

    InternetAddress[] toAddrs = InternetAddress.parse(destEmailAddr, false);
    if (destPersonalName != null) {
      toAddrs[0].setPersonal(destPersonalName);
    }
    InternetAddress from = new InternetAddress(fromEmailAddr);
    from.setPersonal(fromName);

    message.setRecipients(Message.RecipientType.TO, toAddrs);
    message.setFrom(from);
    message.setSubject(emailSubject);
    message.setSentDate(new java.util.Date());

    MimeMultipart msgbody = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setDataHandler(new DataHandler(new MailDataSource(emailPlainText, "text/plain")));
    msgbody.addBodyPart(html);
    message.setContent(msgbody);

    return message;
  }
Exemplo n.º 19
0
  public void enviarEmail() {
    FacesContext context = FacesContext.getCurrentInstance();
    AutenticaUsuario autenticaUsuario =
        new AutenticaUsuario(GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL);
    Session session = Session.getDefaultInstance(this.configuracaoEmail(), autenticaUsuario);
    session.setDebug(true);

    try {

      Transport envio = null;
      MimeMessage email = new MimeMessage(session);
      email.setRecipient(Message.RecipientType.TO, new InternetAddress(this.para));
      email.setFrom(new InternetAddress(this.de));
      email.setSubject(this.assunto);
      email.setContent(this.mensagem, "text/plain");
      email.setSentDate(new Date());
      envio = session.getTransport("smtp");
      envio.connect(GmailBean.SERVIDOR_SMTP, GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL);
      email.saveChanges();
      envio.sendMessage(email, email.getAllRecipients());
      envio.close();

      context.addMessage(null, new FacesMessage("E-mail enviado com sucesso"));

    } catch (AddressException e) {
      FacesMessage msg =
          new FacesMessage("Erro ao montar mensagem de e-mail! Erro: " + e.getMessage());
      context.addMessage(null, msg);
      return;
    } catch (MessagingException e) {
      FacesMessage msg = new FacesMessage("Erro ao enviar e-mail! Erro: " + e.getMessage());
      context.addMessage(null, msg);
      return;
    }
  }
  public static void main(String args[]) throws Exception {
    //
    // create the generator for creating an smime/compressed message
    //
    SMIMECompressedGenerator gen = new SMIMECompressedGenerator();

    //
    // create the base for our message
    //
    MimeBodyPart msg = new MimeBodyPart();

    msg.setText("Hello world!");

    MimeBodyPart mp = gen.generate(msg, new ZlibCompressor());

    //
    // Get a Session object and create the mail message
    //
    Properties props = System.getProperties();
    Session session = Session.getDefaultInstance(props, null);

    Address fromUser = new InternetAddress("\"Eric H. Echidna\"<*****@*****.**>");
    Address toUser = new InternetAddress("*****@*****.**");

    MimeMessage body = new MimeMessage(session);
    body.setFrom(fromUser);
    body.setRecipient(Message.RecipientType.TO, toUser);
    body.setSubject("example compressed message");
    body.setContent(mp.getContent(), mp.getContentType());
    body.saveChanges();

    body.writeTo(new FileOutputStream("compressed.message"));
  }
Exemplo n.º 21
0
 @Override
 public void send() throws MessagingException, UnsupportedEncodingException {
   long t0 = System.currentTimeMillis();
   try {
     if (iMail.getFrom() == null || iMail.getFrom().length == 0)
       setFrom(
           ApplicationProperty.EmailSenderAddress.value(),
           ApplicationProperty.EmailSenderName.value());
     if (iMail.getReplyTo() == null || iMail.getReplyTo().length == 0)
       setReplyTo(
           ApplicationProperty.EmailReplyToAddress.value(),
           ApplicationProperty.EmailReplyToName.value());
     iMail.setSentDate(new Date());
     iMail.setContent(iBody);
     iMail.saveChanges();
     Transport.send(iMail);
   } finally {
     long t = System.currentTimeMillis() - t0;
     if (t > 30000)
       sLog.warn(
           "It took "
               + new DecimalFormat("0.00").format(t / 1000.0)
               + " seconds to send an email.");
     else if (t > 5000)
       sLog.info(
           "It took "
               + new DecimalFormat("0.00").format(t / 1000.0)
               + " seconds to send an email.");
   }
 }
Exemplo n.º 22
0
 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");
   }
 }
Exemplo n.º 23
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);
    }
  }
Exemplo n.º 24
0
 public boolean send() throws Exception {
   Properties props = _setProperties();
   if (!_user.equals("")
       && !_pass.equals("")
       && _to.length > 0
       && !_from.equals("")
       && !_subject.equals("")
       && !_body.equals("")) {
     Session session = Session.getInstance(props, this);
     MimeMessage msg = new MimeMessage(session);
     msg.setFrom(new InternetAddress(_from));
     InternetAddress[] addressTo = new InternetAddress[_to.length];
     for (int i = 0; i < _to.length; i++) {
       addressTo[i] = new InternetAddress(_to[i]);
     }
     msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
     msg.setSubject(_subject);
     msg.setSentDate(new Date()); // setup message body
     BodyPart messageBodyPart = new MimeBodyPart();
     messageBodyPart.setText(_body);
     _multipart.addBodyPart(messageBodyPart); // Put parts in message
     msg.setContent(_multipart); // send email
     Transport.send(msg);
     return true;
   } else {
     return false;
   }
 }
Exemplo n.º 25
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();
    }
  }
Exemplo n.º 26
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);
      }
    }
  }
Exemplo n.º 27
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();
  }
  /*
   * 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();
    }
  }
Exemplo n.º 29
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();
    }
  }
Exemplo n.º 30
0
  public void envia() throws AddressException, MessagingException {
    Session session = Session.getInstance(this.propriedades, this.authentication);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("*****@*****.**"));
    message.setRecipients(Message.RecipientType.TO, "*****@*****.**");
    message.setSentDate(new Date());
    message.setSubject("Teste envio jsf");
    message.setContent("Sua solicitação foi aprovada: OS nº" + this.os, "text/plain");

    Transport.send(message);
  }