/**
   * Initialize this plugin. This method only called when the plugin is instantiated.
   *
   * @param servletConfig Servlet config object for the plugin to retrieve any initialization
   *     parameters
   * @param blojsomConfiguration {@link org.blojsom.blog.BlojsomConfiguration} information
   * @throws BlojsomPluginException If there is an error initializing the plugin
   */
  public void init(ServletConfig servletConfig, BlojsomConfiguration blojsomConfiguration)
      throws BlojsomPluginException {
    String hostname = servletConfig.getInitParameter(SMTPSERVER_IP);

    if (hostname != null) {
      if (hostname.startsWith("java:comp/env")) {
        try {
          Context context = new InitialContext();
          _mailsession = (Session) context.lookup(hostname);
        } catch (NamingException e) {
          _logger.error(e);
          throw new BlojsomPluginException(e);
        }
      } else {
        String username = servletConfig.getInitParameter(SMTPSERVER_USERNAME_IP);
        String password = servletConfig.getInitParameter(SMTPSERVER_PASSWORD_IP);

        Properties props = new Properties();
        props.put(SESSION_NAME, hostname);
        if (BlojsomUtils.checkNullOrBlank(username) || BlojsomUtils.checkNullOrBlank(password)) {
          _mailsession = Session.getInstance(props, null);
        } else {
          _mailsession = Session.getInstance(props, new SimpleAuthenticator(username, password));
        }
      }
    }
  }
示例#2
0
文件: Memo.java 项目: flabser/NB3
  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);
      }
    }
  }
示例#3
0
  public Boolean sendMail(String body, String recept) {

    final String username = "******";
    final String password = "******";

    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    Session session =
        Session.getInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
              }
            });

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress("*****@*****.**"));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recept));
      message.setSubject("*** This is an automatically generated email, please do not reply ***");
      message.setText(
          "Hi there,\n\nPlease find the information you need below:\n"
              + body
              + "\n\nThanks,\n-Kiran");
      Transport.send(message);
      return true;
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
示例#4
0
  public static Session createSmtpSession(
      String host, Integer port, boolean tls, String user, String password) {
    if (Str.isBlank(host)) throw new IllegalArgumentException("host ist blank");

    if (Str.isBlank(user)) user = null;
    if (Str.isBlank(password)) password = null;

    Properties p = new Properties();
    p.setProperty("mail.mime.charset", charset);
    p.setProperty("mail.transport.protocol", "smtp");
    p.setProperty("mail.smtp.host", host);
    if (port != null) p.put("mail.smtp.port", port);
    p.put("mail.smtp.starttls.enable", String.valueOf(tls));

    boolean auth = user != null && password != null;
    p.setProperty("mail.smtp.auth", String.valueOf(auth));
    if (user != null) p.setProperty("mail.smtp.auth.user", user);
    if (password != null) p.setProperty("mail.smtp.auth.password", password);

    Session session = Session.getInstance(p);

    if (auth) {
      session.setPasswordAuthentication(
          new URLName("local"), new PasswordAuthentication(user, password));
    }

    return session;
  }
示例#5
0
  private static void sendSimpleEmails(String toUserName, int count)
      throws MessagingException, InterruptedException, IOException {

    Session session = Session.getInstance(getEmailProperties());

    Random random = new Random();
    int emailSize = emails.length;
    for (int i = 1; i <= count; i++) {
      Thread.sleep(10000);

      MimeMessage msg = new MimeMessage(session);

      InternetAddress from = new InternetAddress(emails[random.nextInt(emailSize)]);

      InternetAddress to = new InternetAddress(toUserName);

      msg.setFrom(from);
      msg.addRecipient(Message.RecipientType.TO, to);
      msg.setSentDate(new Date());

      SimpleMessage randomMessage =
          SimpleMessage.values()[random.nextInt(SimpleMessage.values().length)];
      msg.setSubject(randomMessage.name());
      msg.setText(randomMessage.getBody());
      Transport.send(msg);
    }
  }
示例#6
0
  public void send(String mailto, String subject, String textMessage, String contentType)
      throws FileNotFoundException, MessagingException {
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    Properties props = new Properties();
    props.put("mail.smtp.user", smtpUsername);
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.port", smtpPort);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtps.auth", "true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.socketFactory.port", smtpPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.put("mail.smtp.ssl", "true");

    Authenticator auth = new SMTPAuthenticator();
    Session smtpSession = Session.getInstance(props, auth);
    smtpSession.setDebug(true);

    Message message = new MimeMessage(smtpSession);
    InternetAddress[] address = {new InternetAddress(mailto)};
    message.setRecipients(Message.RecipientType.TO, address);
    message.setSubject(subject);
    message.setSentDate(new Date());
    message.setContent(textMessage, contentType);

    Transport tr = smtpSession.getTransport("smtp");
    tr.connect(smtpHost, smtpUsername, smtpPassword);
    tr.sendMessage(message, message.getAllRecipients());
    tr.close();
  }
示例#7
0
  public static boolean sendEmail(String from, String to, String subject, String message) {
    // create a new authenticator for the SMTP server
    EmailUtilsAuthenticator authenticator = new EmailUtilsAuthenticator();

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

    // Setup mail server
    properties.setProperty(MAIL_SMTP_HOST, Configuration.getSmtpHost());
    // setup the authentication
    properties.setProperty(MAIL_SMTP_AUTH, "true");

    // Get the Session object with the authenticator.
    Session session = Session.getInstance(properties, authenticator);

    try {
      MimeMessage mime = new MimeMessage(session);
      mime.setFrom(new InternetAddress(from));
      mime.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

      mime.setSubject(subject);
      mime.setText(message);

      // Send it
      Transport.send(mime);

      return true;

    } catch (MessagingException mex) {
      logger.error("sendEmail(String, String, String, String) - exception ", mex);
      return false;
    }
  }
示例#8
0
  public static void SendMail(String to, String subject, String Content) {
    try {

      // setup the mail server properties
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");

      // set up the message
      Session session = Session.getInstance(props);

      Message message = new MimeMessage(session);

      // add a TO address
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

      // add a multiple CC addresses
      // message.setRecipients(Message.RecipientType.CC,
      // InternetAddress.parse("[email protected],[email protected]"));

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

      Transport transport = session.getTransport("smtp");
      transport.connect("smtp.gmail.com", 587, "aaa", "pass");
      transport.sendMessage(message, message.getAllRecipients());
      // System.out.println("Send email via gmail...");
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  @Test
  public void testGetFolder() throws MessagingException {
    Properties props;
    Session session;
    Folder folder;
    props = new Properties();

    props.put("mail.host", "pop.gmail.com");
    props.put("mail.store.protocol", "pop3s");
    props.put("mail.pop3s.auth", "true");
    props.put("mail.pop3s.port", 995);

    session = Session.getInstance(props, null);
    Store instance;

    // with wrong param
    instance = session.getStore();
    instance.connect("*****@*****.**", "spamreturn");
    try {
      folder = instance.getFolder("");
    } catch (MessagingException ex) {
      assertTrue(true);
    }

    // with valid param
    try {
      folder = instance.getFolder("INBOX");
      assertTrue(true);
    } catch (MessagingException ex) {
      fail("Should not throw MessagingException");
    }
  }
示例#10
0
  public static void send(String msg) {
    final String fromEmail = "*****@*****.**";
    final String toEmail = "*****@*****.**";
    final String password = "";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Authenticator auth =
        new Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(fromEmail, password);
          }
        };

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

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(fromEmail));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
      message.setSubject("File Uploaded");
      message.setText(msg);

      Transport.send(message);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
  public boolean connectToMailBox() {
    try {
      Properties props = new Properties();
      props.setProperty("mail.imap.ssl.enable", "true"); // required for Gmail
      props.setProperty("mail.imap.auth.mechanisms", "XOAUTH2");
      props.setProperty("mail.store.protocol", config.getString("imap.protocol"));
      props.setProperty("mail.imaps.fetchsize", "" + fetchSize);
      props.setProperty("mail.imaps.timeout", "" + rTimeout);
      props.setProperty("mail.imaps.writetimeout", "" + rTimeout);
      props.setProperty("mail.imaps.connectiontimeout", "" + cTimeout);
      props.setProperty("mail.imaps.connectionpooltimeout", "" + cTimeout);

      Session session = Session.getInstance(props);
      mailbox = session.getStore(config.getString("imap.protocol"));
      mailbox.connect(
          config.getString("imap.host"),
          config.getString("imap.user"),
          config.getString("imap.access_token"));
      LOG.info("Connected to mailbox");
      return true;
    } catch (MessagingException e) {
      LOG.error("Connection failed", e);
      return false;
    }
  }
 public void envioCorreo(String mensaje, String modo) {
   String subject = "";
   String destination = obtenerParametros("destinatario");
   String mailHost = obtenerParametros("mailHost");
   String source = obtenerParametros("origen");
   if (modo.equals("Fallo")) subject = "Aplicaci\363n de Carga y Validaci\363n de datos. ERROR!!";
   else subject = "Aplicacion de Carga y Validaci\363n de datos. MENSAJE INFORMATIVO";
   Properties properties = new Properties();
   properties.put("mail.smtp.host", mailHost);
   properties.put("mail.from", source);
   Session session = Session.getInstance(properties, null);
   try {
     Message message = new MimeMessage(session);
     InternetAddress address[] = {new InternetAddress(destination)};
     message.setRecipients(javax.mail.Message.RecipientType.TO, address);
     message.setFrom(new InternetAddress(source));
     message.setSubject(subject);
     message.setContent(mensaje + "\n", "text/plain");
     Transport transport = session.getTransport(address[0]);
     transport.connect();
     transport.sendMessage(message, address);
   } catch (Exception e1) {
     e1.printStackTrace();
   }
 }
示例#13
0
  private Message createMessage() {

    Properties props = new Properties();

    props.setProperty("mail.transport.protocol", "smtp");

    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.smtp.host", host);
    props.setProperty("mail.smtp.port", "25");

    if (useSSL) {
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.setProperty("mail.smtp.port", "465");
    }

    // error:javax.mail.MessagingException: 501 Syntax: HELO hostname
    props.setProperty("mail.smtp.localhost", "127.0.0.1");

    Session session = Session.getInstance(props, this);
    Message message = new MimeMessage(session);

    try {
      message.setFrom(new InternetAddress(MimeUtility.encodeText(name) + "<" + name + ">"));
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return message;
  }
  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;
  }
示例#15
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);
  }
  public void sendEmail(String email, String password) {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.auth", false);
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", 587);
    Session session =
        Session.getInstance(
            properties,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("*****@*****.**", "test123");
              }
            });

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress("*****@*****.**"));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
      message.setSubject("Reset Password");
      String content = "Your new password is " + password;
      message.setText(content);
      Transport.send(message);

    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
示例#17
0
  public static void sendEmail(String toEmail, String subject, String body) {
    try {

      Properties props = System.getProperties();
      props.put("mail.smtp.host", "mail.excellenceserver.com"); // SMTP Host
      //	        props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
      props.put("mail.smtp.port", "27"); // TLS Port
      props.put("mail.smtp.auth", "true"); // enable authentication
      props.put("mail.smtp.starttls.enable", "true"); // enable STARTTLS

      Authenticator auth =
          new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication("*****@*****.**", "user@#123");
            }
          };
      Session session = Session.getInstance(props, auth);

      MimeMessage msg = new MimeMessage(session);
      // set message headers
      msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
      msg.addHeader("format", "flowed");
      msg.addHeader("Content-Transfer-Encoding", "8bit");
      msg.setFrom(new InternetAddress("*****@*****.**", "user@#123"));
      msg.setReplyTo(InternetAddress.parse("*****@*****.**", false));
      msg.setSubject(subject, "UTF-8");
      msg.setText(body, "UTF-8");
      msg.setSentDate(new Date());
      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

      Transport.send(msg);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#18
0
  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
  /**
   * Sends an email out
   *
   * @param fromAddress
   * @param toAddresses
   * @param strSubject
   * @param strMsg
   */
  public void sendMail(
      String fromAddress,
      String strReplyTo,
      String[] toAddresses,
      String strSubject,
      String strMsg) {
    try {
      Properties props = new Properties();
      props.put("mail.smtp.host", SMTP_HOST);
      Session s = Session.getInstance(props, null);

      MimeMessage message = new MimeMessage(s);

      InternetAddress from = new InternetAddress(fromAddress);
      message.setFrom(from);

      InternetAddress[] addressTo = new InternetAddress[toAddresses.length];
      for (int i = 0; i < toAddresses.length; i++) {
        addressTo[i] = new InternetAddress(toAddresses[i]);
      }
      message.addRecipients(RecipientType.BCC, addressTo);

      message.setSubject(strSubject);
      message.setText(strMsg);
      if (strReplyTo != null) {
        InternetAddress[] iAddress = new InternetAddress[] {new InternetAddress(strReplyTo)};
        message.setReplyTo(iAddress);
      }
      Transport.send(message);
    } catch (Exception e) {
      throw new WickerException(e);
    }
  }
示例#20
0
  // -- MailService overrides
  @Override
  public void send(MailController controller) throws MessagingException {
    if (!controller.hasRecipients()) {
      LOG.warning("Not recipients. No email to send");
      return;
    }

    /* log */

    /* Open the Session */
    Properties properties = new Properties();
    Session session = Session.getInstance(properties, null);
    OptionService os = findService(OptionService.class);
    MimeMessage mm = createMimeMessage(controller, session, os);

    LOG.info("");
    LOG.info(" From:    " + toString(mm.getFrom()));
    LOG.info(" ReplyTo: " + toString(mm.getReplyTo()));
    LOG.info(" Sender:  " + mm.getSender());
    LOG.info(" To:      " + toString(mm.getRecipients(Message.RecipientType.TO)));
    LOG.info(" CC:      " + toString(mm.getRecipients(Message.RecipientType.CC)));
    LOG.info(" Bcc:     " + toString(mm.getRecipients(Message.RecipientType.BCC)));
    LOG.info(" Subject: " + mm.getSubject());
    LOG.info("");

    Transport.send(mm);
  }
  protected void deleteMailsFromUserMailbox(
      final Properties props,
      final String folderName,
      final int start,
      final int deleteCount,
      final String user,
      final String password)
      throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);
    f.open(Folder.READ_WRITE);

    final int msgCount = f.getMessageCount();

    final Message[] m =
        deleteCount == -1
            ? f.getMessages()
            : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1));
    int d = 0;

    for (final Message message : m) {
      message.setFlag(Flag.DELETED, true);
      logger.info(
          "Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject());
      d++;
    }

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();
  }
  public static void main(String[] args) throws Exception {

    final Properties props = new Properties();
    props.load(ClassLoader.getSystemResourceAsStream("mail.properties"));

    Session session =
        Session.getInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    props.getProperty("smtp.username"), props.getProperty("smtp.pass"));
              }
            });

    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(props.getProperty("address.sender")));
    message.setRecipient(
        Message.RecipientType.TO, new InternetAddress(props.getProperty("address.recipient")));
    message.setSubject("Test JavaMail");

    message.setText("Hello!\n\n\tThis is a test message from JavaMail.\n\nThank you.");

    Transport.send(message);

    log.info("Message was sent");
  }
  /**
   * @param config The Properties holding a username, password etc.
   * @param properties Properties holding server settings and configuration
   */
  public ComposeMailScreen(Properties config) {
    this.username = config.getProperty("username");
    Authenticator authenticator =
        new Authenticator() {
          @Override
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
          }
        };

    this.keyWords = new ArrayList<String>();
    this.session = Session.getInstance(config, authenticator);
    // The password which will be decrypted
    String passwordDec = config.getProperty("password");
    try {
      passwordDec = ProtectedPassword.decrypt(passwordDec);
    } catch (GeneralSecurityException ex) {
      JOptionPane.showMessageDialog(
          rootPane, ex.toString(), "GeneralSecurityException", JOptionPane.ERROR_MESSAGE);
    } catch (IOException ex) {
      JOptionPane.showMessageDialog(
          rootPane, ex.toString(), "GeneralSecurityException", JOptionPane.ERROR_MESSAGE);
    }

    this.password = passwordDec;
    initComponents();
    this.setLocationRelativeTo(null);
  }
示例#24
0
  public static void sendMail(String subject, String body) throws IOException, MessagingException {
    final Properties props = new Properties();
    // load a properties file
    props.load(new FileInputStream("mailer.properties"));

    Session session =
        Session.getInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    props.getProperty("user.name"), props.getProperty("user.password"));
              }
            });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(props.getProperty("user.email")));
    message.setRecipients(
        Message.RecipientType.TO, InternetAddress.parse(props.getProperty("user.email")));
    message.setSubject(subject);
    message.setText(body);

    Transport.send(message);

    System.out.println("mail sent");
  }
示例#25
0
  public static int removeEmails(Account account, String protocol)
      throws MessagingException, UnknownHostException {
    int count = 0;
    Session session =
        Session.getInstance(
            Protocol.POP3.equals(protocol)
                ? getPop3MailProperties(account)
                : getImapMailProperties(account));
    Folder inbox;

    //        store = session.getStore("imap");
    if (account.getLoginName().contains("@yahoo.")) {
      IMAPStore imapstore = (IMAPStore) session.getStore(protocol);
      yahooConnect(account, imapstore, true);
      inbox = imapstore.getFolder("INBOX");
    } else {
      Store store = session.getStore(protocol);
      store.connect(account.getReceiveHost(), account.getLoginName(), account.getPassword());
      inbox = store.getFolder("INBOX");
    }

    inbox.open(Folder.READ_WRITE);

    count = inbox.getMessageCount();
    for (Message message : inbox.getMessages()) {
      message.setFlag(Flags.Flag.DELETED, true);
    }
    inbox.close(true);
    return count;
  }
示例#26
0
  protected Spammer() throws MailException {
    final boolean ssl = SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_SSL);

    final String hostProperty = this.hostProperty(ssl);
    final String portProperty = this.portProperty(ssl);
    final String authProperty = this.authProperty(ssl);
    final String localhostProperty = this.localhostProperty(ssl);

    mailProps.put(hostProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST));
    mailProps.put(portProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_PORT));

    String localhost = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_LOCALHOST);

    if (StringUtils.isNotEmpty(localhost)) {
      LOGGER.debug("localhost=" + localhost);
      mailProps.put(localhostProperty, localhost);
    }

    mailProps.put("mail.mime.address.strict", "false");
    mailProps.put("mail.mime.charset", SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET));
    mailProps.put(authProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_AUTH));

    username = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_USERNAME);
    password = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_PASSWORD);

    messageFormat =
        SystemGlobals.getValue(ConfigKeys.MAIL_MESSSAGE_FORMAT).equals("html")
            ? MESSAGE_HTML
            : MESSAGE_TEXT;

    this.session = Session.getInstance(mailProps);
  }
示例#27
0
 public static Session createDummySession() {
   Properties p = new Properties();
   p.setProperty("mail.smtp.host", "localhost");
   p.setProperty("mail.smtp.auth", "true");
   Session session = Session.getInstance(p);
   return session;
 }
  public Session getSession() {
    if (_session != null) {
      return _session;
    }

    Properties properties = new Properties();

    properties.put("mail.debug", String.valueOf(PortletPropsValues.JAVAMAIL_DEBUG));
    properties.put("mail.imap.host", _incomingHostName);
    properties.put("mail.imap.port", _incomingPort);
    properties.put("mail.imaps.auth", "true");
    properties.put("mail.imaps.host", _incomingHostName);
    properties.put("mail.imaps.port", _incomingPort);
    properties.put("mail.imaps.socketFactory.class", SSLSocketFactory.class.getName());
    properties.put("mail.imaps.socketFactory.fallback", "false");
    properties.put("mail.imaps.socketFactory.port", _incomingPort);
    properties.put("mail.smtp.host", _outgoingHostName);
    properties.put("mail.smtp.port", _outgoingPort);
    properties.put("mail.smtps.auth", "true");
    properties.put("mail.smtps.host", _outgoingHostName);
    properties.put("mail.smtps.port", _outgoingPort);
    properties.put("mail.smtps.socketFactory.class", SSLSocketFactory.class.getName());
    properties.put("mail.smtps.socketFactory.fallback", "false");
    properties.put("mail.smtps.socketFactory.port", _outgoingPort);

    _session = Session.getInstance(properties);

    _session.setDebug(PortletPropsValues.JAVAMAIL_DEBUG);

    return _session;
  }
 public EmailChannel(String configuration) {
   Properties props = new Properties();
   try {
     props.load(new StringReader(configuration));
   } catch (IOException e) {
     // really shouldn't happen
     throw new IllegalStateException(
         "Bug: can't load email properties " + "for the channel instance", e);
   }
   String smtpUser = props.getProperty(CFG_USER);
   String smtpPassword = props.getProperty(CFG_PASSWD);
   Authenticator smtpAuthn =
       (smtpUser != null && smtpPassword != null)
           ? new SimpleAuthenticator(smtpUser, smtpPassword)
           : null;
   String trustAll = props.getProperty(CFG_TRUST_ALL);
   if (trustAll != null && "true".equalsIgnoreCase(trustAll)) {
     MailSSLSocketFactory trustAllSF;
     try {
       trustAllSF = new MailSSLSocketFactory();
     } catch (GeneralSecurityException e) {
       // really shouldn't happen
       throw new IllegalStateException("Can't init trust-all SSL socket factory", e);
     }
     trustAllSF.setTrustAllHosts(true);
     props.put("mail.smtp.ssl.socketFactory", trustAllSF);
   } else {
     X509CertChainValidator validator = pkiManagement.getMainAuthnAndTrust().getValidator();
     SSLSocketFactory factory = SocketFactoryCreator.getSocketFactory(null, validator);
     props.put("mail.smtp.ssl.socketFactory", factory);
   }
   session = Session.getInstance(props, smtpAuthn);
 }
示例#30
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;
   }
 }