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
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();
    }
  }
Пример #3
1
  public static void sendMail(String mailMessage) {

    String to = "*****@*****.**";
    String from = "FlotaWeb";
    String host = "mail.arabesque.ro";

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

    Session session = Session.getDefaultInstance(properties);

    try {
      MimeMessage message = new MimeMessage(session);

      message.setFrom(new InternetAddress(from));

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

      message.setSubject("Distributie");

      message.setText(mailMessage);

      Transport.send(message);

    } catch (MessagingException e) {
      logger.error(Utils.getStackTrace(e));
    }
  }
Пример #4
0
 /** Try the given mail server, writing output to the given PrintStream */
 public static void process(String suspect_relay, PrintStream pw) {
   pw.println("processs: trying: " + suspect_relay);
   try {
     // Redirect all output from mail API to the given stream.
     System.setOut(pw);
     System.setErr(pw);
     Sender2 sm = new Sender2(suspect_relay);
     sm.addRecipient("*****@*****.**");
     sm.setFrom(MY_TARGET);
     sm.setSubject("Testing for open mail relay, see " + RSS_SITE);
     sm.setBody(
         "This mail is an attempt to confirm that site "
             + suspect_relay
             + "\n"
             + "is in fact an open mail relay site.\n"
             + "For more information on the problem of open mail relays,\n"
             + "please visit site "
             + RSS_SITE
             + "\n"
             + "Please join the fight against spam by closing all open mail relays!\n"
             + "If this open relay has been closed, please accept our thanks.\n");
     sm.sendFile();
   } catch (MessagingException e) {
     pw.println(e);
   } catch (Exception e) {
     pw.println(e);
   }
 }
Пример #5
0
 public static void main(String[] args) {
   Mail mail = new Mail();
   EmailBuilder emailBuilder =
       new EmailBuilder(EmailProvider.NetEase_163)
           .from(System.getenv("from"))
           .token(System.getenv("token"))
           .to(System.getenv("to"))
           .content("Say something")
           .title("Welcome Letter");
   mail.sendEmail(emailBuilder);
 }
Пример #6
0
  public static void main(String[] args) throws MessagingException, IOException {
    IMAPFolder folder = null;
    Store store = null;
    String subject = null;
    Flag flag = null;
    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");
      props.setProperty("mail.imap.host", "imap.googlemail.com");
      SimpleAuthenticator authenticator =
          new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy");
      Session session = Session.getDefaultInstance(props, null);
      // Session session = Session.getDefaultInstance(props, authenticator);

      store = session.getStore("imaps");
      //          store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");
      // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");

      store.connect("*****@*****.**", "hhy8611hhy");
      // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email
      // account
      folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account

      if (!folder.isOpen()) folder.open(Folder.READ_WRITE);
      Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages();
      System.out.println("No of get Messages : " + messages.length);
      System.out.println("No of Messages : " + folder.getMessageCount());
      System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
      System.out.println("No of New Messages : " + folder.getNewMessageCount());
      System.out.println(messages.length);
      for (int i = 0; i < messages.length; i++) {

        System.out.println(
            "*****************************************************************************");
        System.out.println("MESSAGE " + (i + 1) + ":");
        Message msg = messages[i];
        // System.out.println(msg.getMessageNumber());
        // Object String;
        // System.out.println(folder.getUID(msg)

        subject = msg.getSubject();

        System.out.println("Subject: " + subject);
        System.out.println("From: " + msg.getFrom()[0]);
        System.out.println("To: " + msg.getAllRecipients()[0]);
        System.out.println("Date: " + msg.getReceivedDate());
        System.out.println("Size: " + msg.getSize());
        System.out.println(msg.getFlags());
        System.out.println("Body: \n" + msg.getContent());
        System.out.println(msg.getContentType());
      }
    } finally {
      if (folder != null && folder.isOpen()) {
        folder.close(true);
      }
      if (store != null) {
        store.close();
      }
    }
  }
Пример #7
0
 public boolean isMessageTooOld(Account account, Message message, String context)
     throws MessagingException {
   if (message.getSentDate() == null) {
     log.warn(
         String.format("we have a message with no sent date for %s, allowing message", context));
     return false;
   } else if (account.getRegister_time() == null) {
     log.warn(
         String.format(
             "we are process an account with no register time. this behavior is not understood yet %s, we will accept this message",
             context));
     return false;
   } else {
     boolean messageTooOld =
         (System.currentTimeMillis() - message.getSentDate().getTime())
             > 1000l * 60 * 60 * 24 * emailDaysCutoff;
     if (messageTooOld) {
       log.warn(
           String.format(
               "msgNum=%d, message is too old, sentDate=%s, discarding, for %s",
               message.getMessageNumber(), message.getSentDate(), context));
     }
     return messageTooOld;
   }
 }
Пример #8
0
  public void updateAccount(
      Account account,
      String newFolderHash,
      int newMessages,
      int folderDepth,
      Date lastMessageReceivedDate)
      throws DALException {
    account.setFolder_hash(newFolderHash);
    // reset login failures - since update account happens on successful mail fetch
    account.setLogin_failures(0);
    account.setLast_login_failure(null);

    account.setMessage_count(account.getMessage_count() + newMessages);

    account.setLast_mailcheck(new Date(System.currentTimeMillis()));

    account.setFolder_depth(folderDepth);

    if (lastMessageReceivedDate == null) {
      DALDominator.updateAccountReceiveInfo(account);
    } else {
      account.setLast_received_date(lastMessageReceivedDate);
      DALDominator.updateAccountReceiveInfoAndReceivedDate(account);
    }
  }
Пример #9
0
  public static void main(String[] args) throws MessagingException, IOException {
    Properties props = new Properties();
    try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) {
      props.load(in);
    }
    List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8"));

    String from = lines.get(0);
    String to = lines.get(1);
    String subject = lines.get(2);

    StringBuilder builder = new StringBuilder();
    for (int i = 3; i < lines.size(); i++) {
      builder.append(lines.get(i));
      builder.append("\n");
    }

    Console console = System.console();
    String password = new String(console.readPassword("Password: "));

    Session mailSession = Session.getDefaultInstance(props);
    // mailSession.setDebug(true);
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(builder.toString());
    Transport tr = mailSession.getTransport();
    try {
      tr.connect(null, password);
      tr.sendMessage(message, message.getAllRecipients());
    } finally {
      tr.close();
    }
  }
Пример #10
0
  // reportFileName = TestExecutionResultFileName
  public static void execute(String reportFileName) throws Exception {

    String path = System.getProperty("user.dir") + "/test-output/emailable-report.html";

    String[] to = {"<stakeholder1>", "<stakeholder2>"};
    String[] cc = {};
    String[] bcc = {"<AutomationTester>"};

    SendEmailAdv.sendMail(
        "<AutomationTesterUserName>",
        "<AutomationTesterPassword>",
        "smtp.gmail.com",
        "465",
        "true",
        "true",
        true,
        "javax.net.ssl.SSLSocketFactory",
        "false",
        to,
        cc,
        bcc,
        "<Subject line>",
        "<Contents if any>",
        path,
        reportFileName);
  }
Пример #11
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();
    }
  }
Пример #12
0
 public boolean isTimeToReconcile(Account account) {
   return account.getLast_reconciliation() == null
       || (System.currentTimeMillis() - account.getLast_reconciliation().getTime())
           > 1000l
               * 60
               * Long.valueOf(
                   SysConfigManager.instance().getValue("reconciliationIntervalInMinutes", "60"));
 }
Пример #13
0
 public static void main(String[] args) throws Exception {
   MailClientForCitiz client = new MailClientForCitiz();
   client.init();
   client.sendMessage(client.fromAddr, client.toAddr);
   client.receiveMessage();
   client.close();
   System.exit(0);
 }
Пример #14
0
 public void ensureConnected() throws Exception {
   if (session == null) {
     Properties props = System.getProperties();
     props.setProperty("mail.store.protocol", "imaps");
     props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
     props.setProperty("mail.imap.socketFactory.fallback", "false");
     props.put("mail.smtp.host", getSmtpServer());
     session = Session.getDefaultInstance(props, null);
     store = session.getStore("imaps");
     try {
       store.connect(getServer(), getUsername(), getPassword());
     } catch (MessagingException e) {
       e.printStackTrace();
       System.exit(2);
     }
   }
 }
Пример #15
0
  public void handleLoginFailures(String context, Account account) throws DALException {
    account.setLast_mailcheck(new Date(System.currentTimeMillis()));

    if (account.getLogin_failures() == null) {
      account.setLogin_failures(1);
    } else {
      account.setLogin_failures(account.getLogin_failures() + 1);
    }

    account.setLast_login_failure(new Date(System.currentTimeMillis()));

    DALDominator.updateAccountReceiveInfo(account);

    if (shouldSendAccountLockedNotification(account)) {
      notifyAccountLock(account, context);
      sendAccountLockedNotificationEm(account);
    }
  }
Пример #16
0
  public Message processMessage(
      Account account,
      String messageStoreBucket,
      Message message,
      int messageNumber,
      String messageId,
      String context,
      StopWatch watch,
      List<MessageValidator> validators,
      EmailProcess emailProcess)
      throws Exception {
    long start = System.nanoTime();

    try {
      StopWatchUtils.newTask(
          watch, String.format("msgNum=%s, storeCheck", messageNumber), context, log);
      log.debug(
          String.format(
              "msgNum=%d, checking if messageId=%s is known for %s",
              messageNumber, messageId, context));
      message =
          valiateAndPrepMessage(
              account, messageStoreBucket, message, messageNumber, messageId, validators);
      if (message != null) {
        log.info(
            String.format(
                "msgNum=%d, messageId=%s, message is new for %s",
                messageNumber, messageId, context));
        boolean result = emailProcess.process(message, messageNumber, messageId);
        if (result) {
          return message;
        }
      }
    } finally {
      if (log.isDebugEnabled())
        log.debug(
            String.format(
                "msgNum=%d, checked if messageId=%s is known in %dms for %s",
                messageNumber, messageId, (System.nanoTime() - start) / 1000000, context));
    }

    return null;
  }
Пример #17
0
  public IMAPConnection(URL url) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    //    session.setDebug(true);
    //    try {
    //      session.setDebugOut(new PrintStream(new FileOutputStream("foobar.txt")));
    //    } catch (FileNotFoundException e) {
    //      e.printStackTrace();  //To change body of catch statement use File | Settings | File
    // Templates.
    //    }

    store = (IMAPStore) session.getStore(url.getProtocol());

    String username = null;
    String password = null;

    String userinfo = url.getUserInfo();
    if (userinfo != null) {
      String[] parts = userinfo.split(":");

      username = parts[0].replace('=', '@');

      if (parts.length > 1) password = parts[1];
    }

    if (username == null) username = System.getProperty("imapfs.username");

    if (password == null) password = System.getProperty("imapfs.password");

    store.connect(url.getHost(), username, password);

    String path = url.getPath();
    if (path.startsWith("/")) path = path.substring(1);
    String[] parts = path.split(";");

    if (parts != null && parts.length > 0) this.folder = store.getFolder(parts[0]);
    else this.folder = store.getDefaultFolder();

    if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES);

    folder.open(Folder.READ_WRITE);
  }
Пример #18
0
  public void notifyAccountLock(Account account, String context) {
    PartnerCode partnerCode = account.getPartnerCode();
    String lockedOutMessageBody =
        SysConfigManager.instance()
            .getValue("lockedOutMessageBody", LOCKED_OUT_MESSAGE_BODY, partnerCode);
    String lockedOutMessageSubject =
        SysConfigManager.instance()
            .getValue("lockedOutMessageSubject", LOCKED_OUT_MESSAGE_SUBJECT, partnerCode);
    String lockedOutMessageFrom =
        SysConfigManager.instance()
            .getValue("lockedOutMessageFrom", LOCKED_OUT_MESSAGE_FROM, partnerCode);
    String lockedOutMessageAlias =
        SysConfigManager.instance()
            .getValue("lockedOutMessageAlias", LOCKED_OUT_MESSAGE_ALIAS, partnerCode);

    try {
      Email email = new Email();
      email.setSubject(lockedOutMessageSubject);

      email.setStatus("0");
      email.setUserId(account.getUser_id());
      email.setMessage_type("EMAIL");

      email.setFrom(lockedOutMessageFrom);
      email.setFrom_alias(lockedOutMessageAlias);
      email.setTo(account.getLoginName());
      email.setBodySize(lockedOutMessageBody.length());

      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      email.setMaildate(dateFormat.format(new Date(System.currentTimeMillis()))); // ugh!

      email.setOriginal_account(account.getLoginName());

      // create the pojgo
      EmailPojo emailPojo = new EmailPojo();
      emailPojo.setEmail(email);

      Body body = new Body();
      body.setData(lockedOutMessageBody.getBytes());

      // note, the email will be encoded to prevent sql-injection. since this email is destined
      // directly for the
      // device, we need to reverse the encoding after the call to newSaveEmail
      new EmailRecievedService().newSaveEmail(account, email, body);

      // Added by Dan so we stop checking accounts that have incorrect passwords
      account.setStatus("0");

    } catch (Throwable t) {
      log.warn(String.format("failed to save locked out message for %s", context), t);
    }
  }
  @SuppressWarnings("unused")
  @PostConstruct
  public void init() throws IOException {
    String data_path = System.getenv(OPENSHIFT_DATA_DIR);
    InputStream inputStream = new FileInputStream(data_path + EMAIL_PROPERTIES);
    Properties properties = new Properties();
    properties.load(inputStream);

    this.host = properties.getProperty("host");
    this.from = properties.getProperty("from");
    this.username = properties.getProperty("username");
    this.password = properties.getProperty("password");
  }
  public void sendEMailToUser(ICFSecuritySecUserObj toUser, String msgSubject, String msgBody)
      throws IOException, MessagingException, NamingException {

    final String S_ProcName = "sendEMailToUser";

    Properties props = System.getProperties();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFInternet25SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpEmailFrom");
    }

    smtpUsername = (String) ctx.lookup("java:comp/env/CFInternet25SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFInternet25SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpPassword");
    }

    Session emailSess =
        Session.getInstance(
            props,
            new Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
              }
            });

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(toUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject((msgSubject != null) ? msgSubject : "No subject");
    msg.setSentDate(new Date());
    msg.setContent(msgBody, "text/html");
    msg.saveChanges();

    Transport.send(msg);
  }
Пример #21
0
  public void sendEmail(EmailBuilder builder) {
    // 收件人电子邮箱
    String to = builder.getReceiver();

    // 发件人电子邮箱
    String from = builder.getSender();

    // 获取系统属性
    Properties properties = System.getProperties();

    // 设置邮件服务器
    properties.setProperty("mail.smtp.host", builder.getHost());
    properties.put("mail.smtp.port", builder.getPort());
    properties.put("mail.smtp.auth", builder.authNeeded());

    // 获取默认session对象
    Session session =
        Session.getDefaultInstance(
            properties,
            new Authenticator() {
              public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, builder.getToken()); // 发件人邮件用户名、密码
              }
            });

    try {
      // 创建默认的 MimeMessage 对象
      MimeMessage message = new MimeMessage(session);

      // Set From: 头部头字段
      message.setFrom(new InternetAddress(from));

      message.addRecipients(
          Message.RecipientType.TO,
          new InternetAddress[] {new InternetAddress(to), new InternetAddress(to)});
      // Set Subject: 头部头字段
      message.setSubject(builder.getTitle());

      // 设置消息体
      message.setText(builder.getContent());

      // 发送消息
      Transport.send(message);
      System.out.println("Sent message successfully....from Java Mail");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
  }
  private void SendEmail(String password, String emailTo, String staffNames) {
    // Recipient's email ID needs to be mentioned.
    String to = emailTo;

    // Sender's email ID needs to be mentioned
    String from = "*****@*****.**";

    // Assuming you are sending email from localhost
    String host = "smtp.upcmail.ie";

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
      // Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(session);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));

      // Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

      // Set Subject: header field
      message.setSubject("Password Change From Help Manager");

      // Now set the actual message
      message.setText(
          "Hello "
              + staffNames
              + ", \n\n Your new Password is: "
              + password
              + ".\n\n Regards \n Help Manager Team");

      // Send message
      Transport.send(message);
      System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
  }
Пример #23
0
 public static Session getSession(final SMTPConfig config) {
   // Create some properties and get the default Session.
   Properties props = System.getProperties();
   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.starttls.enable", "true");
   props.put("mail.smtp.starttls.required", "true");
   props.put("mail.smtp.host", config.getHost());
   props.put("mail.smtp.port", config.getPort());
   Session session =
       Session.getInstance(
           props,
           new javax.mail.Authenticator() {
             protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(config.getUsername(), config.getPassword());
             }
           });
   return session;
 }
Пример #24
0
  public synchronized void connect(Properties props) throws Exception {
    String username = getUsername();
    String password = getPassword();
    String server = getServer();

    props.put("mail.smtp.host", getSmtpServer());

    session = Session.getDefaultInstance(props, null);
    store = session.getStore("imaps");

    // smtps://username%[email protected]/

    try {
      store.connect(server, username, password);
    } catch (MessagingException e) {
      e.printStackTrace();
      System.exit(2);
    }
  }
Пример #25
0
 public static void setup(String host, final String username, final String password) {
   Properties p = System.getProperties();
   p.put("mail.transport.protocol", "smtp");
   p.put("mail.smtp.host", host);
   if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
     p.setProperty("mail.smtp.auth", "true");
     session =
         Session.getInstance(
             p,
             new Authenticator() {
               @Override
               protected PasswordAuthentication getPasswordAuthentication() {
                 return new PasswordAuthentication(username, password);
               }
             });
   } else {
     session = Session.getInstance(p);
   }
 }
Пример #26
0
  public void send(
      String from,
      String[] recipientsTo,
      String[] recipientsCC,
      String[] recipientsBCC,
      String subject,
      String body,
      String[] files) {

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

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

      MimeMessage message = new MimeMessage(session);

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

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

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

      setAttachments(files, multipart);

      message.setContent(multipart);

      Transport.send(message);
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
  private Object receiveMail() throws Exception {
    Folder folder = null;
    Store store = null;
    ConfigurationPropertyManager configManager =
        ConfigurationPropertyManager.getConfigurationPropertyManager();
    final String email_address = configManager.getPropValues("gmail_address");
    final String password = configManager.getPropValues("gmail_pw");

    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");

      // Session session = Session.getDefaultInstance(props, null);
      Session session = Session.getInstance(props, new GMailAuthenticator(email_address, password));
      store = session.getStore("imaps");
      store.connect("imap.gmail.com", email_address, password);
      folder = store.getFolder("Inbox");
      folder.open(Folder.READ_WRITE);
      // Message messages[] = folder.getMessages();
      // search for all "unseen" messages
      Flags seen = new Flags(Flags.Flag.SEEN);
      FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
      Message messages[] = folder.search(unseenFlagTerm);

      for (int i = 0; i < messages.length; i++) {
        folder.getMessage(
            messages[i].getMessageNumber()); // this will mark the retrieved messages as READ	    	
      }
      String s = updateEmailrepository(messages);
      // System.out.println(s);
      StringTerm st = new StringTermImpl(s);
      return st;

    } catch (Exception e) {
      System.out.println(e.toString());
    } finally {
      if (folder != null) {
        folder.close(true);
      }
    }
    return null;
  }
  public void sendEmails(Homework hw, ArrayList<Student> students) {
    System.out.println("se apeleza");
    String from = "*****@*****.**";
    String host = "localhost";
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    properties.put("mail.smtp.port", "25");
    Session session = Session.getDefaultInstance(properties);

    try {
      MimeMessage message = new MimeMessage(session);

      message.setFrom(new InternetAddress(from));
      for (Student s : students) {
        System.out.println("baga mesaj catre" + s.getEmail());
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(s.getEmail()));
      }
      message.setSubject("Homework");

      // Send the actual HTML message, as big as you like
      message.setContent(
          "<h1>This is a test mail.</h1>"
              + "<p> It's a program I am developing and I just try to play with the mail API.<p>"
              + "<p> If you're receiving this, please ignore it!</p>"
              + "<p> You're homework is: </p>"
              + "<p>"
              + hw.getDescription()
              + "</p>"
              + "<p> Due Date: "
              + hw.getDueDate()
              + "</p>",
          "text/html");

      // Send message
      Transport.send(message);
      System.out.println(message);
      System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
  }
  private void setProperties() {
    Properties emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", "587");
    emailProperties.put("mail.smtp.auth", "true");
    emailProperties.put("mail.smtp.starttls.enable", "true");

    mailSession = Session.getDefaultInstance(emailProperties, null);
    /** Sender's credentials */
    String user = "******";
    String password = "******";

    String host = "smtp.gmail.com";
    try {
      mailTransport = mailSession.getTransport("smtp");
      mailTransport.connect(host, user, password);
    } catch (NoSuchProviderException e) {
      e.printStackTrace();
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
Пример #30
0
  public static void main(String args[]) throws Exception {
    // String host = args[0];
    // String username = args[1];
    // String password = args[2];

    String host = "triggeremails.com";
    String username = "******";
    String password = "******";

    // Get session
    Session session = Session.getInstance(System.getProperties(), null);

    // Get the store
    Store store = session.getStore("pop3");
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    // Get directory
    Message message[] = folder.getMessages();
    for (int i = 0, n = message.length; i < n; i++) {
      System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject());

      System.out.println("Do you want to delete message? [YES to delete]");
      String line = reader.readLine();
      // Mark as deleted if appropriate
      if ("YES".equals(line)) {
        message[i].setFlag(Flags.Flag.DELETED, true);
      }
    }

    // Close connection
    folder.close(true);
    store.close();
  }