コード例 #1
2
  public static void main(String[] args) {
    String to = "*****@*****.**"; // change accordingly
    String from = "*****@*****.**"; // change accordingly
    String host = "smtp.gmail.com"; // or IP address

    // Get the session object
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(properties);

    // compose the message
    try {
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject("Ping");
      message.setText("Hello, this is example of sending email  ");

      // Send message
      Transport.send(message);
      System.out.println("message sent successfully....");

    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
  }
コード例 #2
0
  protected void loadChildren() {
    try {
      // connect to the Store if we need to
      if (!store.isConnected()) {
        store.connect();
      }

      // get the default folder, and list the
      // subscribed folders on it
      folder = store.getDefaultFolder();
      // Folder[] sub = folder.listSubscribed();
      Folder[] sub = folder.list();

      // add a FolderTreeNode for each Folder
      int num = sub.length;
      for (int i = 0; i < num; i++) {
        FolderTreeNode node = new FolderTreeNode(sub[i]);
        // we used insert here, since add() would make
        // another recursive call to getChildCount();
        insert(node, i);
      }

    } catch (MessagingException me) {
      me.printStackTrace();
    }
  }
コード例 #3
0
  public static boolean sendEmail(String email, String text, String subject) {
    final String username = "******";
    final String password = "******";
    try {
      Properties prop = new Properties();
      prop.put("mail.smtp.auth", "true");
      prop.put("mail.smtp.starttls.enable", "true");
      prop.put("mail.smtp.host", "smtp.gmail.com");
      prop.put("mail.smtp.port", "587");

      Session session =
          Session.getInstance(
              prop,
              new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(username, password);
                }
              });
      try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(username));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        msg.setSubject(subject);
        msg.setText(text);
        Transport.send(msg);
        return true;
      } catch (MessagingException me) {
        me.printStackTrace();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
コード例 #4
0
ファイル: Mailserver.java プロジェクト: shrutie/Foodie
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String email = request.getParameter("email");

    Properties pros = System.getProperties();
    pros.setProperty("mail.smtp.host", "localhost");

    Session mailsession = Session.getDefaultInstance(properties);

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String to = email;
    String from = "*****@*****.**"; // enter the senders email
    String subject = ""; // enter a subject
    String body = "";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(from));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      msg.setSubject(subject);
      msg.setText(body);
      Transport.send(message);
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
コード例 #5
0
 public void logout() throws IOException {
   try {
     store.close();
   } catch (MessagingException e) {
     throw new IOException(e.getMessage());
   }
 }
コード例 #6
0
ファイル: MailUtil.java プロジェクト: yyyfan/xkg
 public boolean send() {
   try {
     MimeMessage msg = javaMailSender.createMimeMessage();
     MimeMessageHelper message = new MimeMessageHelper(msg, true, "UTF-8");
     message.setFrom(from);
     message.setSubject(title);
     message.setTo(toEmails);
     message.setText(getMessage(), true); // 如果发的不是html内容去掉true参数��
     // message.addInline("myLogo",new ClassPathResource("img/mylogo.gif"));
     // message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf"));
     javaMailSender.send(msg);
   } catch (MessagingException e) {
     e.printStackTrace();
     if (log.isWarnEnabled()) {
       log.warn("邮件信息导常! 邮件标题为: " + title);
     }
     return false;
   } catch (MailException me) {
     me.printStackTrace();
     if (log.isWarnEnabled()) {
       log.warn("发送邮件失败! 邮件标题为: " + title);
     }
     return false;
   }
   return true;
 }
コード例 #7
0
  /** Sends a list of reservations in one message. */
  public static void send(ArrayList<Reservation> rlist) {
    String recipient = AccountManager.getEmail(rlist.get(0).name);
    if (recipient == null) return;

    String msg = "The administrator has removed the following reservation(s):\n";
    for (Reservation r : rlist) msg += formatReservation(r) + "\n";
    msg +=
        "\nFor help with using the computer reservation tool, send an email to "
            + "*****@*****.**";

    try {
      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(email));

      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
      message.setSubject("Your computer reservation(s) have been removed");
      message.setText(msg);

      Transport.send(message);
      Server.println("Email sent to " + recipient);

    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
コード例 #8
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null);
    SendMail sm = new SendMail();
    String br = "\n";

    try {
      // 受信メールを取得
      MimeMessage recMsg = new MimeMessage(session, req.getInputStream());

      DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      String sentDate = df.format(recMsg.getSentDate());
      String from = recMsg.getFrom().toString();
      String subject = recMsg.getSubject();
      String content = this.getText(recMsg.getContent());

      String msgBody = "";
      msgBody += "sent at : " + sentDate + br;
      msgBody += "from : " + from + br;
      msgBody += "subject : " + subject + br;
      msgBody += "-----------content----------" + br + content;
      sm.send("*****@*****.**", "", "sutekitest転送", msgBody);
    } catch (MessagingException e) {
      sm.send("*****@*****.**", "", "sutekitestメール受信エラー", e.getMessage() + br + e.getCause());
    }
  }
コード例 #9
0
ファイル: Utils.java プロジェクト: spl/Beta-SMS
  public void sendMail(String id, String mail) {
    System.out.println("In de send mail method");
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String msgBody =
        "Dear Beta-SMS user,\n Thank you for submiting a feature/issue request. You can follow the status at http://beta-sms.coralic.nl?TABTOSELECT=tab-todo&ID="
            + id
            + "\n \n Thank you for using Beta-SMS.";

    try {
      System.out.println("Building the email and trying to send it");
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "beta-sms.coralic.nl Beta-SMS"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mail, mail));
      msg.setSubject("Beta-SMS feature/issue request processed.");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (AddressException e) {
      System.err.println(e.getMessage());
    } catch (MessagingException e) {
      System.err.println(e.getMessage());
    } catch (UnsupportedEncodingException e) {
      System.err.println(e.getMessage());
    }
  }
コード例 #10
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;
  }
コード例 #11
0
ファイル: Send.java プロジェクト: KodyKantor/MailClient
 /** Sends the message. Uses superclass username, pass, host, etc. */
 public void sendMessage() {
   if (text == null) {
     text = asker.askOpenEnded("Please enter a message to send: ");
   }
   if (destination == null) {
     while (destination == null) {
       try {
         destination =
             new InternetAddress(asker.askOpenEnded("Please enter a message recipient: "));
       } catch (AddressException e) {
         System.out.println("Sorry, you entered an invalid email address.");
       }
     }
   }
   if (subject == null) {
     subject = asker.askOpenEnded("Please enter a subjectJ: ");
   }
   try {
     MimeMessage msg = new MimeMessage(super.session);
     msg.setSubject(this.subject);
     msg.setText(this.text);
     msg.setFrom(new InternetAddress(super.username));
     msg.addRecipient(Message.RecipientType.TO, this.destination);
     Transport t = super.session.getTransport("smtps");
     t.connect(super.host, super.username, super.password);
     t.sendMessage(msg, msg.getAllRecipients());
   } catch (MessagingException mex) {
     throw new MailException(mex.getMessage());
   }
   super.addMessagesToDB();
   System.out.println("Successfully sent message.");
 }
コード例 #12
0
  private static Folder getMailInbox(Store store) {

    Folder folder = null;
    Folder inboxfolder = null;

    try {
      folder = store.getDefaultFolder();
      if (folder == null) throw new Exception("No default folder");
      inboxfolder = folder.getFolder("INBOX");
      if (inboxfolder == null) throw new Exception("No INBOX");
      inboxfolder.open(Folder.READ_ONLY);

      Message[] msgs = inboxfolder.getMessages();

      FetchProfile fp = new FetchProfile();
      fp.add("Subject");
      inboxfolder.fetch(msgs, fp);
      return inboxfolder;

    } catch (NoSuchProviderException ex) {
      ex.printStackTrace();
    } catch (MessagingException ex) {
      ex.printStackTrace();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {

    }

    return null;
  }
コード例 #13
0
ファイル: SendMessage.java プロジェクト: FRA-UAS/Mailer
  private void setTextArea() {

    String date = "";
    String from = "";
    String to = "";

    to = removeFirstSpace(messageHandler.getToText());

    try {

      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/YYYY hh:mm a");
      date = simpleDateFormat.format(message.getSentDate());
      from = getFrom();
    } catch (MessagingException e) {
      e.printStackTrace();
    }

    referenceTextArea = textArea;

    textArea.setText(
        "\n\n\n"
            + ">Date: "
            + date
            + "\n"
            + ">From: "
            + from
            + "\n>To: "
            + to
            + "\n>"
            + messageHandler.getText());

    textArea.setCaretPosition(0);
  }
コード例 #14
0
 /**
  * Handles the HTTP <code>POST</code> method.
  *
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   try {
     String removeKey = request.getParameter(RemoveParameter);
     if (removeKey != null) {
       remove(removeKey, response);
     } else {
       try {
         BlogAuthor blogAuthor = setNamespace(request, response);
         if (blogAuthor == null) {
           return;
         }
         handleMail(request, response, blogAuthor);
       } catch (MessagingException ex) {
         log(ex.getMessage(), ex);
         response.sendError(HttpServletResponse.SC_CONFLICT);
       } catch (EntityNotFoundException ex) {
         log(ex.getMessage(), ex);
         response.sendError(HttpServletResponse.SC_FORBIDDEN);
       }
     }
   } catch (HttpException ex) {
     log(ex.getMessage(), ex);
     ex.sendError(response);
   }
 }
コード例 #15
0
 /**
  * 以文本格式发送邮件
  *
  * @param mailInfo 待发送的邮件信息
  */
 public static boolean sendTextMail(MailSenderInfo mailInfo) {
   // 判断是否需要身份认证
   MailAuthenticator authenticator = null;
   Properties pro = mailInfo.getProperties();
   if (mailInfo.isValidate()) {
     // 如果需要身份认证,则创建一个密码验证器
     authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
   }
   // 根据邮件会话属性和密码验证器构造一个发送邮件的session
   Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
   try {
     // 根据session创建一个邮件消息
     Message mailMessage = new MimeMessage(sendMailSession);
     // 创建邮件发送者地址
     Address from = new InternetAddress(mailInfo.getFromAddress());
     // 设置邮件消息的发送者
     mailMessage.setFrom(from);
     // 创建邮件的接收者地址,并设置到邮件消息中
     Address to = new InternetAddress(mailInfo.getToAddress());
     mailMessage.setRecipient(Message.RecipientType.TO, to);
     // 设置邮件消息的主题
     mailMessage.setSubject(mailInfo.getSubject());
     // 设置邮件消息发送的时间
     mailMessage.setSentDate(new Date());
     // 设置邮件消息的主要内容
     String mailContent = mailInfo.getContent();
     mailMessage.setText(mailContent);
     // 发送邮件
     Transport.send(mailMessage);
     return true;
   } catch (MessagingException ex) {
     ex.printStackTrace();
   }
   return false;
 }
コード例 #16
0
  @Override
  protected void doDisconnect() throws Exception {
    // close and expunge deleted messages
    try {
      if (folder != null) {
        try {
          folder.expunge();
        } catch (MessagingException e) {
          if (logger.isDebugEnabled()) {
            logger.debug("ignoring exception on expunge: " + e.getMessage());
          }
        }
        if (folder.isOpen()) {
          folder.close(true);
        }
      }
    } catch (Exception e) {
      logger.error("Failed to close inbox: " + e.getMessage(), e);
    }

    try {
      if (moveToFolder != null) {
        if (moveToFolder.isOpen()) {
          moveToFolder.close(false);
        }
      }
    } catch (Exception e) {
      logger.error("Failed to close moveToFolder: " + e.getMessage(), e);
    }
  }
コード例 #17
0
ファイル: Mail.java プロジェクト: joensen/Aarhus-Cafekirke
  public boolean send() {

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
      fromAddress = new InternetAddress(from);
      toAddress = new InternetAddress(to);
    } catch (AddressException e) {
      e.printStackTrace();
      return false;
    }

    try {
      simpleMessage.setFrom(fromAddress);
      simpleMessage.setRecipient(RecipientType.TO, toAddress);
      simpleMessage.setSubject(subject);
      simpleMessage.setText(text);

      Transport.send(simpleMessage);
      return true;
    } catch (MessagingException e) {
      e.printStackTrace();
      return false;
    }
  }
コード例 #18
0
ファイル: Mailer.java プロジェクト: StephenJMoore/MovieKiosk
  public void mail(String toAddress, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.ssl.enable", true);
    Authenticator authenticator = null;
    if (login) {
      props.put("mail.smtp.auth", true);
      authenticator =
          new Authenticator() {
            private PasswordAuthentication pa = new PasswordAuthentication(username, password);

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

    Session s = Session.getInstance(props, authenticator);
    s.setDebug(debug);
    MimeMessage email = new MimeMessage(s);
    try {
      email.setFrom(new InternetAddress(from));
      email.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
      email.setSubject(subject);
      email.setSentDate(new Date());
      email.setText(body);
      Transport.send(email);
    } catch (MessagingException ex) {
      ex.printStackTrace();
    }
  }
コード例 #19
0
ファイル: FolderTableModel.java プロジェクト: zieglerm/enh
 public FolderTableModel() {
   try {
     setFolder(null);
   } catch (MessagingException ex) {
     ex.printStackTrace();
   }
 }
コード例 #20
0
 private EmailAddressList addRecipientsAux(
     final javax.mail.Message.RecipientType recipientType,
     final EmailAddressList emailAddressList) {
   final String[] emailAddresses = emailAddressList.toArray();
   for (int i = 0; i < emailAddresses.length; i++) {
     final String emailAddress = emailAddresses[i];
     try {
       if (emailAddressFormatIsValid(emailAddress)) {
         addRecipient(recipientType, new InternetAddress(encode(emailAddress)));
       } else {
         logProblem("invalid.email.address.format: " + emailAddress);
       }
     } catch (final AddressException e) {
       logProblem(e.getMessage() + " " + emailAddress);
     } catch (final MessagingException e) {
       logProblem(e.getMessage() + " " + emailAddress);
     }
     if (i == MAX_MAIL_RECIPIENTS && i + 1 < emailAddresses.length) {
       final String all = emailAddressList.toString();
       final int next = all.indexOf(emailAddress) + emailAddress.length() + 2;
       return new EmailAddressList(all.substring(next));
     }
   }
   return null;
 }
コード例 #21
0
ファイル: EmailNotifier.java プロジェクト: rayaPajohesh/nli
 private int execute(String[] args) {
   if (args.length != 1) {
     System.err.println("Usage: EmailNotifier path-to-property-file");
     return -1;
   }
   File f = new File(args[0]);
   FileInputStream in;
   try {
     in = new FileInputStream(f);
   } catch (FileNotFoundException e) {
     System.err.println("Property file not found:" + f.getAbsolutePath());
     return -2;
   }
   Properties props = new Properties();
   try {
     props.load(in);
   } catch (IOException e) {
     System.err.println("Can not read from property file.");
     return -3;
   }
   try {
     sendMail(props);
   } catch (MessagingException e) {
     System.err.println("Failed to send mail.");
     e.printStackTrace();
     return -4;
   }
   return 0;
 }
コード例 #22
0
  public void sendMail(String plainText, String htmlText, String attachment) {

    MimeMessage message = mailSender.createMimeMessage();
    try {
      MimeMessageHelper helper = new MimeMessageHelper(message, true);
      helper.setFrom(simpleMailMessage.getFrom());
      helper.setTo(simpleMailMessage.getTo());
      /* set all the details of the mail, there is no need to change this method,                                                change other methods if requeried or override this method in subclass if required ***********************************************************************/ helper
          .setBcc("*****@*****.**");
      /* plantext null will not work on plain html*/
      helper.setSubject(simpleMailMessage.getSubject());
      helper.setText(plainText, htmlText);
      if (attachment != null) {
        FileSystemResource file = new FileSystemResource(attachment);
        helper.addAttachment(file.getFilename(), file);
      }
      mailSender.send(message);
    } catch (MessagingException e) {
      System.out.print(e.getMessage());
      logger.error("Exception in Method:sendMail", e);
    } catch (Exception ex) {
      System.out.print(ex.getMessage());
      logger.error("Exception in Method:sendMail", ex);
    }
  }
コード例 #23
0
 /** Return the content. */
 public Object getContent(DataSource ds) throws IOException {
   // create a new DeliveryStatus
   try {
     /*
        Session session;
        if (ds instanceof MessageAware) {
     javax.mail.MessageContext mc =
     	((MessageAware)ds).getMessageContext();
     session = mc.getSession();
        } else {
     // Hopefully a rare case.  Also hopefully the application
     // has created a default Session that can just be returned
     // here.  If not, the one we create here is better than
     // nothing, but overall not a really good answer.
     session = Session.getDefaultInstance(new Properties(), null);
        }
        return new DeliveryStatus(session, ds.getInputStream());
        */
     return new DeliveryStatus(ds.getInputStream());
   } catch (MessagingException me) {
     throw new IOException(
         "Exception creating DeliveryStatus in "
             + "message/delivery-status DataContentHandler: "
             + me.toString());
   }
 }
コード例 #24
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;
    }
  }
コード例 #25
0
  public void SendEmail(String email, String contestToken) {
    String to = email;
    String from = "Tyumen_ACM_Society";
    String host = "smtp.gmail.com";
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", host);
    props.put("mail.stmp.user", "*****@*****.**");
    props.put("mail.smtp.password", "475508th");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");

    Session session = Session.getDefaultInstance(props, new SmtpAuthenticator());

    try {
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject("Registration on acm.utmn.ru");
      message.setText(
          "Hello! Thank you for registration on acm.utmn.ru! Use next token to submit tasks: "
              + contestToken);
      Transport t = session.getTransport("smtp");
      t.send(message);
      System.out.println("Message was successfully sent.");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
  }
コード例 #26
0
  @Test
  public void testByteArrayToSMIME() {
    try {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      TEST_CASE1.writeTo(out);
      ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());

      ByteArraytoSMIME transformer = new ByteArraytoSMIME();

      Object object = transformer.transformMimeMessage(in, null);
      assertNotNull(object);
      assertTrue(object instanceof MimeMultipart);

      MimeMultipart mime = (MimeMultipart) object;

      assertEquals(TEST_CASE1.getBodyPart(0).getContent(), mime.getBodyPart(0).getContent());
      assertEquals(TEST_CASE1.getBodyPart(1).getContent(), mime.getBodyPart(1).getContent());

    } catch (TransformerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      fail();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      fail();
    } catch (MessagingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      fail();
    }
  }
コード例 #27
0
  public void sendMail(String From, String To, String subject, String body) {

    Properties props = new Properties();

    props.put("mail.smtp.user", "*****@*****.**");
    props.put("mail.smtp.host", "smtp.gmail.com");

    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.fallback", "false");

    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", " javax.net.ssl.SSLSocketFactory");

    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session =
        Session.getDefaultInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("*****@*****.**", "password");
              }
            });
    //
    // session.setDebug(true);

    try {

      Message message = new MimeMessage(session);

      message.setFrom(new InternetAddress(From));

      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To));
      message.setSubject(subject);
      message.setText(body);

      Transport transport = session.getTransport("smtps");
      transport.connect(
          "smtp.gmail.com", Integer.valueOf(465), "*****@*****.**", "password;");
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();

      // System.out.println("Done");

      // } catch (MessagingException e) {
    } catch (AddressException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MessagingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (Exception e) {
      throw new RuntimeException(e.toString());
    }
  }
コード例 #28
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();
    }
  }
 public void sincronizarSeguimientos()
     throws ErrorSQLException, FaltaParametroException, EmailException {
   Date hoy = new Date();
   List<Seguimiento> listSeguimientos = this.seguimientoDao.obtenerSeguimientos(hoy);
   if (listSeguimientos != null && listSeguimientos.size() > 0) {
     Iterator<Seguimiento> it = listSeguimientos.iterator();
     String mensajeaEnviar = "";
     while (it.hasNext()) {
       Seguimiento seguimiento = it.next();
       Actividad actividad = seguimiento.getActividad();
       if (seguimiento.getFechaVencimiento() == hoy) {
         mensajeaEnviar =
             Constantes.PLANTILLA_MENSAJE_VENCE
                 + actividad.getTitulo()
                 + Constantes.PLANTILLA_MENSAJE_CLIENTE
                 + seguimiento.getActividad().getOportunidad().getEmpresa().getNombre();
       } else {
         mensajeaEnviar =
             actividad.getTitulo()
                 + Constantes.PLANTILLA_MENSAJE_CLIENTE
                 + seguimiento.getActividad().getOportunidad().getEmpresa().getNombre();
       }
       Iterator<Seguimientotiposeguimiento> itTipos =
           seguimiento.getSeguimientotiposeguimientos().iterator();
       while (itTipos.hasNext()) {
         Seguimientotiposeguimiento tipoSeguimiento = itTipos.next();
         if (tipoSeguimiento
             .getTiposeguimiento()
             .getNombre()
             .equalsIgnoreCase(Constantes.NOMBRE_EMAIL)) {
           try {
             EmailUtiles.envioMail(
                 Constantes.ENVIO_TITULO_VENCIMIENTO,
                 mensajeaEnviar,
                 seguimiento.getUsuario().getEmail());
             seguimiento.setEnviado(1);
             seguimientoDao.modificarSeguimiento(seguimiento);
           } catch (MessagingException ex) {
             LOGGER.error(ex.getMessage(), ex);
             throw new EmailException();
           }
         } else {
           try {
             String celular = seguimiento.getUsuario().getCelular().toString();
             EmailUtiles.envioMail(
                 Constantes.ENVIO_TITULO_VENCIMIENTO,
                 mensajeaEnviar,
                 celular + Constantes.EMAIL_MOVISTAR);
             seguimiento.setEnviado(1);
             seguimientoDao.modificarSeguimiento(seguimiento);
           } catch (MessagingException ex) {
             LOGGER.error(ex.getMessage(), ex);
             throw new EmailException();
           }
         }
       }
     }
   }
 }
コード例 #30
0
ファイル: StoreTest.java プロジェクト: zhangxiaov/AndroidOS
 public void testGetFolder() {
   try {
     Folder f = store.getFolder(url.getFile());
     assertNotNull(f);
   } catch (MessagingException e) {
     fail(e.getMessage());
   }
 }