Esempio n. 1
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;
    }
  }
Esempio n. 2
0
 /**
  * Send a message (in MimeMessage representation).
  *
  * @param _m the message to send
  * @throws MessagingException the messaging exception
  */
 public void send(MimeMessage _m) throws MessagingException {
   TRANSPORT.connect(
       CONFIG.getProperty("mail.host"),
       CONFIG.getProperty("mail.user"),
       CONFIG.getProperty("mail.password"));
   TRANSPORT.sendMessage(_m, _m.getAllRecipients());
 }
Esempio n. 3
0
  public void test() throws Exception {

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

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

    String s = msgfield.getText();
    message.setContent(s, "text/plain");
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailID.getText()));
    System.out.println("8i m here ");
    try {
      transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, username.getText(), password.getText());
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, "invalid username or password");
    }
    System.out.println("8i m here also yaar");
    // transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
    transport.sendMessage(message123, message123.getAllRecipients());
    transport.close();
    System.out.println(s);
  }
Esempio n. 4
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();
    }
  }
Esempio n. 5
0
  private static void sendMimeMessage(
      String from,
      String to,
      String subject,
      String content,
      List<String> filenames,
      Session session) {

    try {
      String[] toArr = {to};
      DataSource[] attachments = (filenames == null) ? null : new DataSource[filenames.size()];

      if (filenames != null) {
        int i = 0;
        for (String filename : filenames) {
          attachments[i++] = new FileDataSource(filename);
        }
      }

      MimeMessage message = createMimeMessage(session, from, toArr, subject, content, attachments);
      message.saveChanges();

      Transport transport = session.getTransport();
      try {
        transport.connect();
        transport.sendMessage(message, message.getAllRecipients());
      } finally {
        transport.close();
      }
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
Esempio n. 6
0
  @Override
  public void send(MimeMessage message) throws MailerException {
    Session session = Session.getDefaultInstance(getConfiguration());

    if (this.from != null) {
      try {
        message.setFrom(from);
      } catch (MessagingException e) {
        throw new MailerException(e);
      }
    }

    try {
      Transport tr = session.getTransport("smtp");
      if (getConfigurationProperty(Configuration.SMTP.AUTH, "true").equalsIgnoreCase("true")) {
        tr.connect(
            getConfigurationProperty(Configuration.SMTP.USER),
            getConfigurationProperty(Configuration.SMTP.PASSWORD));
      } else {
        tr.connect();
      }
      tr.sendMessage(message, message.getAllRecipients());
      tr.close();
    } catch (MessagingException e) {
      throw new MailerException(e);
    }
  }
Esempio n. 7
0
  /**
   * main de prueba
   *
   * @param args Se ignoran.
   */
  public static void main(String[] args) {
    try {
      // Propiedades de la conexión
      Properties props = new Properties();
      props.setProperty("mail.smtp.host", "smtp.gmail.com");
      props.setProperty("mail.smtp.starttls.disable", "true");
      props.setProperty("mail.smtp.auth.plain.disable", "true");
      props.setProperty("mail.smtp.port", "465");
      props.setProperty("mail.smtp.user", "*****@*****.**");
      props.setProperty("mail.smtp.auth", "true");

      // Preparamos la sesion
      Session session = Session.getDefaultInstance(props);
      session.setDebug(true);
      // Construimos el mensaje
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress("*****@*****.**"));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress("*****@*****.**"));
      message.setSubject("Hola");
      message.setText("Mensajito con Java Mail" + "de los buenos." + "poque si");

      // Lo enviamos.
      Transport t = session.getTransport("smtp");
      t.connect("*****@*****.**", "admmphinv2012");
      t.sendMessage(message, message.getAllRecipients());

      // Cierre.
      t.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 8
0
 /** 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.");
 }
  @Test
  public void shouldNotMatchMessageWithoutRecipient() throws MessagingException {
    when(address1.toString()).thenReturn("*****@*****.**");
    when(address2.toString()).thenReturn("*****@*****.**");

    when(message.getAllRecipients()).thenReturn(new Address[] {address1, address2});

    assertThat(message, not(HasRecipient.hasRecipient("*****@*****.**")));
  }
Esempio n. 10
0
 public void sendEmail(Session session, MimeMessage message) throws MessagingException {
   Transport transport = session.getTransport("smtp");
   try {
     transport.connect();
     transport.sendMessage(message, message.getAllRecipients());
   } finally {
     transport.close();
   }
 }
Esempio n. 11
0
 public void sendEmailUsingJava(String to, String content, String subjectContext) {
   // int smtpPort = 465;
   // int smtpPort = 587;
   // String smtpHost = "smtp.gmail.com";
   // int smtpPort = 25;
   // String smtpHost = "exsmtp.wvu.edu";
   String subject = constants.getString(subjectContext);
   int smtpPort = Integer.parseInt(constants.getString("smtpPort"));
   String smtpHost = constants.getString("smtpHost");
   String urPassword = constants.getString("password");
   String from = constants.getString("emailaddress");
   // String content = contentText;
   // Create a mail session
   java.util.Properties props = new java.util.Properties();
   props = System.getProperties();
   props.put("mail.smtp.host", smtpHost);
   // props.put("mail.smtp.starttls.enable", "true");
   props.put("mail.smtps.auth", "true");
   SmtpAuthenticator authentication = new SmtpAuthenticator();
   // Session session = Session.getInstance(props, null);
   Session session = Session.getInstance(props, authentication);
   session.setDebug(true);
   // Construct the message
   try {
     MimeMessage msg = new MimeMessage(session);
     msg.setFrom(new InternetAddress(from));
     msg.setRecipient(RecipientType.TO, new InternetAddress(to));
     msg.setSubject(subject);
     msg.setText(content);
     msg.setSentDate(new Date());
     Transport tr = null;
     tr = session.getTransport("smtp");
     tr.connect(smtpHost, smtpPort, from, urPassword);
     tr.sendMessage(msg, msg.getAllRecipients());
   } catch (AddressException e) {
     System.out.println(e.getClass().getName() + ": " + e.getMessage());
     Log.info(e.getClass().getName() + ": " + e.getMessage());
     StackTraceElement[] trace = e.getStackTrace();
     for (int i = 0; i < trace.length; i++) {
       System.out.println("\t" + trace[i].toString());
       Log.info("\n\t" + trace[i].toString());
     }
     e.printStackTrace();
   } catch (MessagingException e) {
     System.out.println(e.getClass().getName() + ": " + e.getMessage());
     Log.info(e.getClass().getName() + ": " + e.getMessage());
     StackTraceElement[] trace = e.getStackTrace();
     for (int i = 0; i < trace.length; i++) {
       System.out.println("\t" + trace[i].toString());
       Log.info("\n\t" + trace[i].toString());
     }
     e.printStackTrace();
   }
 }
  /**
   * @param MostrarInforme Abre una ventana con el informe del email
   * @param SERVIDOR
   * @param PUERTO
   */
  public boolean sendMailHTML(boolean MostrarInforme, String SERVIDOR, String PUERTO) {
    if (MostrarInforme) {
      Informe.setVisible(true);
      Informe.setAlwaysOnTop(true);
    }
    try {
      Informe.setTitulo("Destino: " + Destinatarios.get(0));
      Properties props = new Properties();
      props.put("mail.smtp.host", SERVIDOR); // "wo06.wiroos.com" o "smtp.gmail.com"
      props.setProperty("mail.smtp.starttls.enable", "true");
      //          props.setProperty("mail.smtp.port", "587");
      props.setProperty("mail.smtp.port", PUERTO); // "587");
      props.setProperty("mail.smtp.user", usuarioCorreo);
      props.setProperty("mail.smtp.auth", "true");

      Session session = Session.getDefaultInstance(props, null);
      BodyPart texto = new MimeBodyPart();
      texto.setText(mensaje);

      BodyPart adjunto = new MimeBodyPart();
      if (!rutaArchivo.equals("")) {
        adjunto.setDataHandler(new DataHandler(new FileDataSource(rutaArchivo)));
        adjunto.setFileName(nombreArchivo);
      }

      MimeMultipart multiParte = new MimeMultipart();
      multiParte.addBodyPart(texto);
      if (!rutaArchivo.equals("")) {
        multiParte.addBodyPart(adjunto);
      }

      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(usuarioCorreo));

      // Destinatarios varios
      for (int i = 0; i < Destinatarios.size(); i++) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(Destinatarios.get(i)));
        message.setSubject(asunto);
      }
      message.setContent(mensaje, "text/html");
      Informe.SetConectando();
      Transport t = session.getTransport("smtp");
      t.connect(usuarioCorreo, password);
      Informe.SetEnviando();
      t.sendMessage(message, message.getAllRecipients());
      t.close();
      Informe.SetEnviado(true);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      Informe.SetEnviado(false);
      return false;
    }
  }
Esempio n. 13
0
  public EmailMessage parseToBetterFormat(MimeMessage m) {
    try {
      EmailMessage email = new EmailMessage();
      Address[] senders = m.getFrom();
      if ((senders == null) || senders.length != 1) {
        LOG.severe("ignoring incoming email with null or multiple from's: " + senders);
        return null;
      }
      email.from = new InternetAddress(senders[0].toString());

      Address[] recipients = m.getAllRecipients();
      if (recipients == null) {
        LOG.severe("ignoring incoming email with null recipient list from sender: " + email.from);
        return null;
      }
      email.to = Lists.newArrayList();

      for (Address a : recipients) {
        email.to.add(new InternetAddress(a.toString()));
      }

      email.subject = m.getSubject();

      String contentType = m.getContentType();
      if (!contentType.startsWith("text/plain;") && !contentType.startsWith("text/html;")) {
        LOG.log(Level.WARNING, "ignoring message with unrecognized content type" + contentType);
        return null;
      }
      try {
        // This is stupid, but I've seen both ByteArrayInputStream and String,
        // and the interface doesn't specify one.
        Object o = m.getContent();
        if (o instanceof String) {
          email.body = (String) o;
        } else if (o instanceof ByteArrayInputStream) {
          ByteArrayInputStream stream = (ByteArrayInputStream) o;
          byte[] bytes = new byte[stream.available()];
          stream.read(bytes);
          email.body = new String(bytes);
        }
      } catch (IOException e) {
        LOG.log(
            Level.SEVERE,
            "Caught exception while trying to read content of email from " + email.from,
            e);
        return null;
      }

      return email;
    } catch (MessagingException e) {
      LOG.log(Level.SEVERE, "Couldn't parse incoming email", e);
      return null;
    }
  }
Esempio n. 14
0
 private void logMail(MimeMessage msg) {
   try {
     String to = "";
     Address[] toAddresses = msg.getAllRecipients();
     if (toAddresses.length == 1) {
       to = toAddresses[0].getType();
     } else if (toAddresses.length > 1) {
       to = toAddresses[0].getType() + " and  #" + (msg.getAllRecipients().length - 1) + " other";
     } else {
       to = "NO-TO-ADDRESS";
     }
     log.info("Mail Test-Mode: Would send mail to=" + to + " with subject=" + msg.getSubject());
     if (log.isDebugEnabled()) {
       log.debug("Mail Test-Mode: from=" + msg.getFrom()[0]);
       log.debug("Mail Test-Mode: content=" + msg.getContent() + "'");
     }
   } catch (Exception e) {
     log.warn("Could not extract log-info from mime-message, ", e);
   }
 }
Esempio n. 15
0
 public static Map<String, Object> mcaTest(DispatchContext dctx, Map<String, ?> context) {
   MimeMessageWrapper wrapper = (MimeMessageWrapper) context.get("messageWrapper");
   MimeMessage message = wrapper.getMessage();
   try {
     if (message.getAllRecipients() != null) {
       Debug.log("To: " + UtilMisc.toListArray(message.getAllRecipients()), module);
     }
     if (message.getFrom() != null) {
       Debug.log("From: " + UtilMisc.toListArray(message.getFrom()), module);
     }
     Debug.log("Subject: " + message.getSubject(), module);
     if (message.getSentDate() != null) {
       Debug.log("Sent: " + message.getSentDate().toString(), module);
     }
     if (message.getReceivedDate() != null) {
       Debug.log("Received: " + message.getReceivedDate().toString(), module);
     }
   } catch (Exception e) {
     Debug.logError(e, module);
   }
   return ServiceUtil.returnSuccess();
 }
  /**
   * Sends an email to someone We require the email address of the receipt, the subject, and the
   * body The ID is used to identify an email when the user replies back
   */
  public void sendEmail(String id, String to, String subject, String body) throws Exception {

    String replyTo = createRecipientWithId(id);
    Properties props = prepareEmailSenderProperties();

    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = prepareEmailSenderMessage(session, to, replyTo, subject, body);

    Transport transport = prepareEmailSenderTransport(session);
    transport.connect(senderHost, emailAddress, emailPassword);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
  }
Esempio n. 17
0
  public void sendEmail() throws MessagingException {
    try {
      Transport transport = mailSession.getTransport("smtp");
      transport.connect(emailHost, fromEmail, fromPassword);

      transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
      transport.close();

    } catch (AuthenticationFailedException afe) {
      afe.printStackTrace();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Esempio n. 18
0
  /** Prepares message and sends it. Returns Message ID of sent email. */
  public String sendMail(Email mail) {
    MimeMessage msg;
    try {
      msg = createMessage(mail, mailSession);
    } catch (MessagingException mex) {
      throw new MailException("Failed to prepare email: " + mail, mex);
    }
    try {
      mailTransport.sendMessage(msg, msg.getAllRecipients());

      return msg.getMessageID();
    } catch (MessagingException mex) {
      throw new MailException("Failed to send email: " + mail, mex);
    }
  }
Esempio n. 19
0
  /**
   * Rigourous Test :-)
   *
   * @throws Exception
   */
  public void testSMTP() throws Exception {

    MimeMessage message = new MimeMessage(session);

    message.setContent("Hello", "text/html");
    message.setSubject("First mail");
    message.setFrom(new InternetAddress("*****@*****.**", "Advalso"));
    message.addRecipient(
        MimeMessage.RecipientType.TO, new InternetAddress("*****@*****.**", "Maurizio Branca"));

    Transport t = session.getTransport("smtp");

    t.connect();
    t.sendMessage(message, message.getAllRecipients());
    t.close();
  }
Esempio n. 20
0
  // =========================================================================
  @Override
  public void run() {

    if (from == null || to == null || subject == null || message == null) {
      thrower.nullPointerException("some parameters are null or empty");
      return;
    }

    Properties props = null;
    Session session = null;
    MimeMessage msg = null;
    Transport t = null;

    try {

      props = new Properties();
      props.setProperty("mail.smtp.host", "smtp.gmail.com");
      props.setProperty("mail.smtp.starttls.enable", "true");
      props.setProperty("mail.smtp.port", "587");
      props.setProperty("mail.smtp.user", this.gmailUser);
      props.setProperty("mail.smtp.auth", "true");

      session = Session.getDefaultInstance(props);

      msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(this.from));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(this.to));
      msg.setSubject(this.subject);
      msg.setText(this.message);

      t = session.getTransport("smtp");
      t.connect(this.gmailUser, this.gmailPassword);
      t.sendMessage(msg, msg.getAllRecipients());

      t.close();

    } catch (Exception e) {
      thrower.exception(e);
    } finally {
      t = null;
      props = null;
      session = null;
      msg = null;
    }
  } // end run
  public void sendText(String subject, String textMessage, String... emails) {
    setProperties();
    MimeMessage message = new MimeMessage(mailSession);

    try {
      for (String email : emails) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
      }
      message.setSubject(subject);
      message.setText(textMessage);

      mailTransport.sendMessage(message, message.getAllRecipients());
      mailTransport.close();

    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
Esempio n. 22
0
  public boolean sendMail() {
    prepare();
    try {
      MimeMessage mimeMessage = new MimeMessage(session);
      mimeMessage.setFrom(new InternetAddress(from));
      InternetAddress address = new InternetAddress(taxPayer.getEmail());
      mimeMessage.addRecipient(RecipientType.TO, address);

      mimeMessage.setSubject("Татварын ерөнхий газар өр дуудах төв ");
      mimeMessage.setText(message());

      MimeMultipart multipart = new MimeMultipart("related");

      BodyPart messageBodyPart = new MimeBodyPart();
      String htmlText = "<H1>МТА ӨР ДУУДАХ ТӨВ</H1><img src=\"cid:image\">";
      htmlText += "<br>" + message();
      messageBodyPart.setContent(htmlText, "text/html;charset=UTF-8");

      multipart.addBodyPart(messageBodyPart);
      /*
      			messageBodyPart = new MimeBodyPart();
      			DataSource fds = new FileDataSource(
      					"C:/Users/Suld/Pictures/image.jpg");

      			messageBodyPart.setDataHandler(new DataHandler(fds));
      			messageBodyPart.setHeader("Content-ID", "<image>");
      */
      multipart.addBodyPart(messageBodyPart);

      mimeMessage.setContent(multipart);

      Transport transport = session.getTransport("smtp");
      transport.connect(host, from, password);
      transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
      transport.close();
      return true;
    } catch (AddressException e) {
      e.printStackTrace();
    } catch (MessagingException e) {
      e.printStackTrace();
    }
    return false;
  }
  public void apply() {
    User user = db.emailExist(email);
    if (user.getEmail() != null) {
      Properties props = System.getProperties();

      props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.from", "*****@*****.**");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.port", "587");
      props.setProperty("mail.debug", "true");

      Session session = Session.getDefaultInstance(props);
      try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("*****@*****.**"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));

        message.setSubject("This is the Subject Line!");

        String newPw = gen.nextSessionId();
        user.setPassword(newPw);
        if (db.changePassword(user)) {
          message.setText(
              "Hi,\n \n You requested a reset of your password."
                  + "\n \n Your new password is now: "
                  + newPw);
          Transport transport = session.getTransport("smtp");
          transport.connect("*****@*****.**", "catering123");
          transport.sendMessage(message, message.getAllRecipients());
          transport.close();
          System.out.println("Sent message successfully....");
        }
        FacesMessage fm = new FacesMessage("Email sent");
        FacesContext.getCurrentInstance().addMessage(null, fm);
      } catch (MessagingException mex) {
        mex.printStackTrace();
        //   }
      }
    } else {
      FacesMessage fm = new FacesMessage("Email was not found");
      FacesContext.getCurrentInstance().addMessage(null, fm);
    }
  }
Esempio n. 24
0
  @Override
  public void send(String to, String subject, String text) {
    Session session = Session.getDefaultInstance(properties, null);

    // TODO: Should be refactored.
    try {
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(user));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject(subject);
      message.setText("Quantity: " + text);

      Transport transport = session.getTransport();
      transport.connect(user, pass);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
    } catch (Exception e) {
      throw new MailReporterException(e.getMessage());
    }
  }
Esempio n. 25
0
  public void sendMail(String para, String asunto, String mensaje) {
    if (!existe()) {
      configurar();
    }

    try {
      Properties propiedades = new Properties();
      propiedades.load(new FileInputStream(RUTA));

      String email = propiedades.getProperty("email");
      String pass = propiedades.getProperty("pass");

      Properties mailServerProperties;
      Session getMailSession;
      MimeMessage generateMailMessage;

      mailServerProperties = System.getProperties();
      mailServerProperties.put("mail.smtp.port", "587");
      mailServerProperties.put("mail.smtp.auth", "true");
      mailServerProperties.put("mail.smtp.starttls.enable", "true");

      getMailSession = Session.getDefaultInstance(mailServerProperties, null);
      generateMailMessage = new MimeMessage(getMailSession);
      generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(para));
      generateMailMessage.setSubject(asunto);
      generateMailMessage.setContent(mensaje, "text/html");

      Transport transport = getMailSession.getTransport("smtp");

      transport.connect("smtp.gmail.com", email, pass);
      // transport.connect("smtp.gmail.com", "*****@*****.**", "iwanna666");
      transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
      transport.close();
    } catch (MessagingException ex) {
      Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
      Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Esempio n. 26
0
  String sendMail(String sends, String subject, String msg) {
    if (!isSend) return "发送失败,未开启发送功能";
    if (null == msg || "".equals(msg)) return "内容为空";
    if (null == sends || "".equals(sends)) return "收件人为空";

    String result = "";
    try {
      Properties props = new Properties();
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.auth", true);
      Session session = Session.getDefaultInstance(props, null);
      session.setDebug(false);

      MimeMessage mimeMessage = new MimeMessage(session);
      mimeMessage.setFrom(new InternetAddress(fromMail));
      sends = sends.replace(",", ",");
      String[] tomails = StrUtils.split(sends, ',');
      InternetAddress[] internetAddresses = new InternetAddress[tomails.length];
      if (null != tomails && tomails.length > 0) {
        for (int i = 0; i < tomails.length; i++) {
          internetAddresses[i] = new InternetAddress(tomails[i].trim());
        }
      }

      mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses);
      mimeMessage.setSentDate(new Date());
      mimeMessage.setSubject(subject);
      mimeMessage.setContent(msg, "text/html;charset=UTF-8");
      mimeMessage.saveChanges(); // 存储邮件信息

      Transport transport = session.getTransport("smtp");
      transport.connect(host, fromMail, pwd); // 以smtp方式登录邮箱
      transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); // 发送邮件,其中第二个参数是所有
      transport.close();
      result = "邮件发送成功:" + sends;
    } catch (Exception e) {
      e.printStackTrace();
      result = "邮件发送失败:" + sends;
    }
    return result;
  }
Esempio n. 27
0
  public static void exec(String mailbox, String title, String content) throws Exception {

    String mail_from = MailBean.mailAddress; // mailbox 发送到哪 title 标题
    Properties props = new Properties();

    props.put("mail.smtp.host", MailBean.mailServer);

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

    Session s = Session.getInstance(props);

    s.setDebug(true);

    MimeMessage message = new MimeMessage(s);

    InternetAddress from = new InternetAddress(mail_from);

    message.setFrom(from);

    InternetAddress to = new InternetAddress(mailbox);

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

    message.setSubject(title);

    message.setText(content);

    message.setContent(content, "text/html;charset=gbk");

    message.setSentDate(new Date());

    message.saveChanges();

    Transport transport = s.getTransport("smtp");

    transport.connect(MailBean.mailServer, MailBean.mailCount, MailBean.mailPassword);

    transport.sendMessage(message, message.getAllRecipients());

    transport.close();
  }
Esempio n. 28
0
 /* (non-Javadoc)
  * @see uk.ac.hpcx.model.helpdesk.MessageProvider#getRecipients()
  */
 public final String getRecipients() {
   try {
     MimeMessage m = getMessage();
     if (m == null) {
       return "";
     }
     StringBuilder sb = new StringBuilder();
     javax.mail.Address[] recip = m.getAllRecipients();
     if (recip != null && recip.length > 0) {
       sb.append(recip[0]);
       for (int i = 1; i < recip.length; i++) {
         sb.append(", ");
         sb.append(recip[i]);
       }
     }
     return sb.toString();
   } catch (Exception e) {
     getContext().error(e, "Error getting recipients");
   }
   return "";
 }
Esempio n. 29
0
  private static void sendFromGMail(
      String from, String pass, String to, String subject, String body) {
    Properties props = System.getProperties();
    String host = "smtp.gmail.com";
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {
      message.setFrom(new InternetAddress(from));
      // InternetAddress[] toAddress = new InternetAddress[to.length];

      // To get the array of addresses
      /*for( int i = 0; i < to.length; i++ ) {
          toAddress[i] = new InternetAddress(to[i]);
      }*/

      /*for( int i = 0; i < toAddress.length; i++) {
          message.addRecipient(Message.RecipientType.TO, toAddress[i]);
      }*/

      message.setSubject(subject);
      message.setText(body);
      Transport transport = session.getTransport("smtp");
      transport.connect(host, from, pass);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
    } catch (AddressException ae) {
      ae.printStackTrace();
    } catch (MessagingException me) {
      me.printStackTrace();
    }
  }
Esempio n. 30
0
  private void replyMail(
      Session session, String smtpHost, String username, String password, String comment)
      throws Exception { // �ظ��ʼ�

    Log.v("YYC", "mimeMsg------>" + mimeMsg);
    MimeMessage msg = (MimeMessage) this.mimeMsg.reply(false);
    msg.setFrom(new InternetAddress(username));
    msg.setRecipients(Message.RecipientType.TO, from);
    Multipart mp = new MimeMultipart();
    MimeBodyPart mbp = new MimeBodyPart();
    mbp.setContent(
        "<meta http-equiv=Content-Type content=text/html; charset=GBK>" + comment,
        "text/html;charset=gb2312");
    mp.addBodyPart(mbp);
    msg.setContent(mp);
    msg.setSentDate(new Date());
    msg.saveChanges();
    Transport trans = session.getTransport("smtp");
    trans.connect(smtpHost, username, password);
    trans.sendMessage(msg, msg.getAllRecipients());
    trans.close();
  }