示例#1
0
  public void send() {
    // Your SMTP server address here.
    String smtpHost = "myserver.jeffcorp.com";
    // The sender's email address
    String from = "*****@*****.**";
    // The recepients email address
    String to = "*****@*****.**";

    Properties props = new Properties();
    // The protocol to use is SMTP
    props.put("mail.smtp.host", smtpHost);

    Session session = Session.getDefaultInstance(props, null);

    try {
      InternetAddress[] address = {new InternetAddress(to)};
      MimeMessage message;

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

      message.setRecipients(Message.RecipientType.TO, to);
      message.setSubject("Hello from Jeff");
      message.setSentDate(sendDate);
      message.setText("Hello Jeff, \nHow are things going?");

      Transport.send(message);

      System.out.println("email has been sent.");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
示例#2
0
  /**
   * Este método é responsável por enviar email.
   *
   * @param pServidorSMTP
   * @param pDe
   * @param pPara
   * @param pCopia
   * @param pBcc
   * @param pAssunto
   * @param pTexto
   * @return true se o email for enviado, false caso contrário.
   */
  public static boolean enviarEmail(
      final String pServidorSMTP,
      final String pDe,
      final String pPara,
      final String pCopia,
      final String pBcc,
      final String pAssunto,
      final String pTexto) {

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

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

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

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

      // Atribuir assunto
      msg.setSubject(pAssunto);

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

      msg.setSentDate(new Date());

      Transport.send(msg);

      msg = null;
      mailSession = null;
    } catch (MessagingException mex) {
      if (Constants.DEBUG) {
        mex.printStackTrace(System.out);
      }
      return false;
    }
    return true;
  }
示例#3
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();
    }
  }
示例#4
0
文件: MailUtil.java 项目: wyona/lenya
  /**
   * Generate a MimeMessage with the specified attributes
   *
   * @param destEmailAddr The destination email address
   * @param fromEmailAddr The sender email address
   * @param fromName The senders display name
   * @param emailSubject The subject
   * @param emailPlainText The message body (plaintext)
   * @return The MimeMessage object
   * @throws Exception
   */
  public static MimeMessage generateMail(
      String destEmailAddr,
      String destPersonalName,
      String fromEmailAddr,
      String fromName,
      String emailSubject,
      String emailPlainText)
      throws Exception {

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

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

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

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

    return message;
  }
  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;
    }
  }
示例#6
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);
    }
  }
示例#7
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();
    }
  }
示例#8
0
 @Override
 public void send() throws MessagingException, UnsupportedEncodingException {
   long t0 = System.currentTimeMillis();
   try {
     if (iMail.getFrom() == null || iMail.getFrom().length == 0)
       setFrom(
           ApplicationProperty.EmailSenderAddress.value(),
           ApplicationProperty.EmailSenderName.value());
     if (iMail.getReplyTo() == null || iMail.getReplyTo().length == 0)
       setReplyTo(
           ApplicationProperty.EmailReplyToAddress.value(),
           ApplicationProperty.EmailReplyToName.value());
     iMail.setSentDate(new Date());
     iMail.setContent(iBody);
     iMail.saveChanges();
     Transport.send(iMail);
   } finally {
     long t = System.currentTimeMillis() - t0;
     if (t > 30000)
       sLog.warn(
           "It took "
               + new DecimalFormat("0.00").format(t / 1000.0)
               + " seconds to send an email.");
     else if (t > 5000)
       sLog.info(
           "It took "
               + new DecimalFormat("0.00").format(t / 1000.0)
               + " seconds to send an email.");
   }
 }
示例#9
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;
   }
 }
  public void sendOTPToEmail(String to, String subject, String Username, String Password) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    switch (protocol) {
      case SMTPS:
        props.put("mail.smtp.ssl.enable", true);
        break;
      case TLS:
        props.put("mail.smtp.starttls.enable", true);
        break;
    }

    Authenticator authenticator = null;
    if (auth) {
      props.put("mail.smtp.auth", true);
      authenticator =
          new Authenticator() {
            private PasswordAuthentication pa = new PasswordAuthentication(username, password);

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

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

    MimeMessage message = new MimeMessage(session);
    try {
      message.setFrom(new InternetAddress(from));
      InternetAddress[] address = {new InternetAddress(to)};
      message.setRecipients(Message.RecipientType.TO, address);
      message.setSubject(subject);
      message.setSentDate(new Date());
      /* message.setText(body); */
      Multipart multipart = new MimeMultipart("alternative");

      MimeBodyPart textPart = new MimeBodyPart();
      // If email client does not support html-------------------------
      String textContent = "Username: "******" Password:"******"<html><h1>QCollect "
              + "</h1><p><h3>Please Use the following OTP to login to your Account</h3></p>"
              + Password
              + "</p></html>";
      htmlPart.setContent(htmlContent, "text/html");
      multipart.addBodyPart(textPart);
      multipart.addBodyPart(htmlPart);
      message.setContent(multipart);
      Transport.send(message);
    } catch (MessagingException ex) {
      ex.printStackTrace();
    }
  }
 /**
  * Send the message with given send date.
  *
  * @param date send date, can be null
  * @return sent {@link MimeMessage}
  * @throws MessagingException
  * @throws IOException
  */
 public MimeMessage send(Date date) throws MessagingException, IOException {
   final MimeMessage message = build();
   try {
     message.setSentDate(date);
   } catch (Exception e) {
   }
   Transport.send(message);
   return message;
 }
 private void sendEmail(String subject, String body, String to) throws MessagingException {
   log.debug("Sending e-mail message to '" + to + "' with subject: " + subject);
   MimeMessage msg = new MimeMessage(session);
   msg.setFrom();
   msg.setRecipients(Message.RecipientType.TO, to);
   msg.setSubject(subject);
   msg.setSentDate(new Date());
   msg.setText(body);
   Transport.send(msg);
 }
示例#13
0
  public void sendEmail() throws MessagingException {
    if (msg.getFrom() == null)
      msg.setFrom(new InternetAddress("*****@*****.**"));
    msg.setHeader("X-mailer", "msgsend");
    msg.setRecipients(Message.RecipientType.TO, (Address[]) toList.toArray(new Address[0]));
    msg.setRecipients(Message.RecipientType.CC, (Address[]) ccList.toArray(new Address[0]));
    msg.setRecipients(Message.RecipientType.BCC, (Address[]) bccList.toArray(new Address[0]));
    msg.setSentDate(new Date());

    if (!toList.isEmpty()) Transport.send(msg);
  }
示例#14
0
  public void envia() throws AddressException, MessagingException {
    Session session = Session.getInstance(this.propriedades, this.authentication);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("*****@*****.**"));
    message.setRecipients(Message.RecipientType.TO, "*****@*****.**");
    message.setSentDate(new Date());
    message.setSubject("Teste envio jsf");
    message.setContent("Sua solicitação foi aprovada: OS nº" + this.os, "text/plain");

    Transport.send(message);
  }
示例#15
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();
   }
 }
示例#16
0
  public static Boolean sendFeedbackEmail(CustomerFeedback customerFeedback) {

    Properties mailProps = new Properties();
    mailProps.setProperty("mail.smtp.host", onemenuMailHostName);
    mailProps.setProperty("mail.smtp.starttls.enable", "true");
    mailProps.setProperty("mail.smtp.auth", "true");
    mailProps.setProperty("mail.smtp.quitwait", "false");
    mailProps.setProperty("mail.smtp.ssl.trust", "*");

    Authenticator authenticator = new EmailAuthenticator(onemenuMailAddress, onemenuPassword);

    javax.mail.Session mailSession =
        javax.mail.Session.getDefaultInstance(mailProps, authenticator);

    try {

      Address fromAddress = new InternetAddress(onemenuMailAddress);
      Address toAddress = new InternetAddress(onemenuMailAddress);
      // modify by file 本处不用使用StringBuffer,Stringbuffer
      // 是线程安全的,性能不如StringBuilder(所有本身是线程安全的代码都不应该使用StringBuffer)
      // StringBuffer contentBuffer = new StringBuffer();
      StringBuilder contentBuilder = new StringBuilder();
      contentBuilder
          .append("<p>" + customerFeedback.getmCustomerEmail() + "</p>")
          .append("<p>" + customerFeedback.getmCustomerName() + ":</p>")
          .append("<p>" + customerFeedback.getmContent() + "</p>");
      String content = contentBuilder.toString();

      MimeMessage msg = new MimeMessage(mailSession);
      msg.setFrom(fromAddress);
      msg.setSubject("[OneMenu Feedback] ");
      msg.setSentDate(new Date());
      msg.setContent(content, "text/html;charset=utf-8");
      msg.setRecipient(RecipientType.TO, toAddress);

      /*
       * Transport transport = session.getTransport("smtp"); transport.connect("smtp.163.com",
       * userName, password); transport.sendMessage(msg,msg.getAllRecipients());
       * transport.close();
       */

      Transport.send(msg);
      if (LOGGER.isDebugEnabled()) LOGGER.debug("Send feedback email.");

    } catch (MessagingException e) {
      LOGGER.error("", e);
    }

    return true;
  }
  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);
  }
  protected void putMailInMailbox(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
      final MimeMessage message = new MimeMessage((Session) null);
      message.setFrom(new InternetAddress(EMAIL_TO));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
      message.setSubject(EMAIL_SUBJECT + "::" + i);
      message.setText(EMAIL_TEXT + "::" + SID++);
      message.setSentDate(new Date());
      MockMailbox.get(EMAIL_USER_ADDRESS).getInbox().add(message);
    }

    logger.info("Putted " + messages + " into mailbox");
  }
示例#19
0
  private static MimeMessage createMessage(
      String from, String[] to, String subject, MimeMultipart content) throws MessagingException {
    Session session = Session.getInstance(System.getProperties());
    session.setDebug(true);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));

    for (String aTo : to) {
      message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(aTo, false));
    }

    message.setSubject(subject);
    message.setContent(content);
    message.setHeader("X-Mailer", "iComp");
    message.setSentDate(new Date());
    return message;
  }
示例#20
0
  /**
   * Funkcija za slanje poruke koja se poziva pritiskom na gumb unutar prikaza slanja poruka.
   *
   * @return
   */
  public String saljiPoruku() {
    EmailPovezivanje ep =
        (EmailPovezivanje)
            FacesContext.getCurrentInstance()
                .getExternalContext()
                .getSessionMap()
                .get("emailPovezivanje");
    this.emailPosluzitelj = ep.getEmailPosluzitelj();

    try {
      // Create the JavaMail session
      java.util.Properties properties = System.getProperties();
      properties.put("mail.smtp.host", this.emailPosluzitelj);

      Session session = Session.getInstance(properties, null);

      // Construct the message
      MimeMessage message = new MimeMessage(session);
      // Set the from address
      Address fromAddress = new InternetAddress(this.saljePoruku);
      message.setFrom(fromAddress);
      // Parse and set the recipient addresses
      Address[] toAddresses = InternetAddress.parse(this.primaPoruku);
      message.setRecipients(Message.RecipientType.TO, toAddresses);
      // Set the subject and text
      message.setSubject(this.predmetPoruke);
      message.setText(this.sadrzajPoruke);
      message.setSentDate(new Date());

      Transport.send(message);
      this.uspjesnoPoslano = true;
      this.primaPoruku = null;
      this.predmetPoruke = null;
      this.sadrzajPoruke = null;
      System.out.println("Slanje poruke uspješno");

    } catch (AddressException e) {
      e.printStackTrace();
    } catch (SendFailedException e) {
      e.printStackTrace();
    } catch (MessagingException e) {
      e.printStackTrace();
    }
    return null;
  }
 public static void sendMail(
     String smtpServer, String from, String to, String subject, String body) {
   try {
     MimeMessage msg = new MimeMessage(getMailSession(smtpServer));
     msg.setFrom(new InternetAddress(from));
     msg.setRecipients(Message.RecipientType.TO, to);
     if (subject == null || subject.equals("")) {
       subject = TEXT_NO_SUBJECT;
     }
     msg.setSubject(subject);
     msg.setText(body, "UTF-8");
     msg.setSentDate(new Date());
     //
     Transport.send(msg);
   } catch (Throwable e) {
     throw new DeepaMehtaException(e.toString(), e);
   }
 }
  public void send(String title, String[] receiver, String content) {

    Properties properties = new Properties();

    try {
      properties.load(getClass().getResourceAsStream("/config/emailauth.properties"));

      Authenticator authenticator =
          new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication(
                  properties.getProperty("mail.smtp.user"),
                  properties.getProperty("mail.smtp.password"));
            }
          };

      Session session = Session.getInstance(properties, authenticator);
      session.setDebug(false);

      MimeMessage message = new MimeMessage(session);

      message.addHeader("Content-type", "text/HTML; charset=UTF-8");
      message.addHeader("format", "flowed");
      message.addHeader("Content-Transfer-Encoding", "8bit");

      message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.user"), "관리자"));
      message.setReplyTo(InternetAddress.parse(properties.getProperty("mail.smtp.user"), false));

      message.setSubject(title, "UTF-8");
      message.setText(content, "UTF-8");
      message.setSentDate(new Date());

      for (int i = 0; i < receiver.length; i++) {
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver[i], false));
      }
      Transport.send(message);

    } catch (IOException ie) {
      // TODO Auto-generated catch block
      ie.printStackTrace();
    } catch (MessagingException me) {
      me.printStackTrace();
    }
  }
示例#23
0
  private static void sendBigEmail(String toUserName) throws MessagingException, IOException {
    Session session = Session.getInstance(getEmailProperties());

    Random random = new Random();
    int emailSize = emails.length;
    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.setSubject("New book  " + UUID.randomUUID().toString());

    // create and fill the first message part
    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText("Hi, all \n I sent you book.\n  Thank you, ");

    // create the second message part
    MimeBodyPart mbp2 = new MimeBodyPart();

    // attach the file to the message
    FileDataSource fds = new FileDataSource(new ClassPathResource(BIG_FILE).getFile());
    mbp2.setDataHandler(new DataHandler(fds));
    mbp2.setFileName(fds.getName());

    // create the Multipart and add its parts to it
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);
    mp.addBodyPart(mbp2);

    // add the Multipart to the message
    msg.setContent(mp);

    // set the Date: header
    msg.setSentDate(new Date());
    //                    msg.setText(String.format(TEXT, name));

    // send message
    Transport.send(msg);
  }
示例#24
0
  public void sendMessage(NMessage m) throws Exception {
    ensureConnected();

    // Create a new message with values from dialog.
    MimeMessage newMessage = new MimeMessage(session);
    newMessage.setFrom(new InternetAddress(from /* m.getFrom() */));

    newMessage.setSubject(m.getName());
    newMessage.setSentDate(m.getWhen());
    newMessage.setContent(m.getContent(), "text/html");

    final Address[] recipientAddresses = InternetAddress.parse(m.getTo());
    newMessage.setRecipients(Message.RecipientType.TO, recipientAddresses);

    Transport transport = session.getTransport("smtps");
    transport.connect(getSmtpServer(), GMAIL_SMTP_PORT, getUsername(), getPassword());
    transport.sendMessage(newMessage, recipientAddresses);
    transport.close();
  }
示例#25
0
  /**
   * 此段代码用来发送普通电子邮件
   *
   * @throws MessagingException
   * @throws UnsupportedEncodingException
   * @throws UnsupportedEncodingException
   */
  public void send() throws MessagingException, UnsupportedEncodingException {
    Properties props = new Properties();
    Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(props, auth);
    // 设置session,和邮件服务器进行通讯。
    MimeMessage message = new MimeMessage(session);
    // message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
    message.setSubject(mail_subject); // 设置邮件主题
    message.setText(mail_body); // 设置邮件正文
    message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题

    message.setSentDate(new Date()); // 设置邮件发送日期
    Address address = new InternetAddress(mail_from, personalName);
    message.setFrom(address); // 设置邮件发送者的地址
    Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Transport.send(message); // 发送邮件
  }
示例#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;
  }
 private void sendMail(CorporateDirectives directives) throws DeepaMehtaException {
   try {
     Hashtable props = getProperties();
     if (!props.get(PROPERTY_STATUS).equals(EMAIL_STATE_DRAFT)) {
       return;
     }
     // error check
     Vector recipients = collectRecipients();
     if (recipients.size() == 0) {
       // ### TODO: error notification (or disable "Send" command in advance?)
       return;
     }
     // create message
     MimeMessage msg = new MimeMessage(getMailSession(as.getSMTPServer()));
     // set sender
     String author = (String) props.get(PROPERTY_FROM);
     logger.info(this + ", author=\"" + author + "\"");
     msg.setFrom(new InternetAddress(author));
     // set recipients
     setRecipients(msg, recipients);
     // set subject
     String subject = (String) props.get(PROPERTY_SUBJECT);
     if (subject == null || subject.equals("")) {
       subject = TEXT_NO_SUBJECT;
     }
     msg.setSubject(subject);
     // set date
     Date d = new Date();
     msg.setSentDate(d);
     // set text and attachments
     String msgText = (String) props.get(PROPERTY_TEXT);
     addAttachments(msgText, msg);
     //
     Transport.send(msg);
     //
     setProperty(PROPERTY_STATUS, EMAIL_STATE_SENT);
     setProperty(PROPERTY_DATE, d.toString());
   } catch (Throwable e) {
     throw new DeepaMehtaException(e.toString(), e);
   }
 }
示例#28
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();
  }
示例#29
0
    /**
     * Send an email to the admin address
     *
     * @throws IOException
     * @throws ServletException
     * @throws InterruptedException
     */
    public FormValidation doSendTestMail(
        @QueryParameter String smtpServer,
        @QueryParameter String adminAddress,
        @QueryParameter boolean useSMTPAuth,
        @QueryParameter String smtpAuthUserName,
        @QueryParameter String smtpAuthPassword,
        @QueryParameter boolean useSsl,
        @QueryParameter String smtpPort)
        throws IOException, ServletException, InterruptedException {
      try {
        if (!useSMTPAuth) smtpAuthUserName = smtpAuthPassword = null;

        MimeMessage msg =
            new MimeMessage(
                createSession(
                    smtpServer,
                    smtpPort,
                    useSsl,
                    smtpAuthUserName,
                    Secret.fromString(smtpAuthPassword)));
        msg.setSubject("Test email #" + ++testEmailCount);
        msg.setContent(
            "This is test email #"
                + testEmailCount
                + " sent from Hudson Continuous Integration server.",
            "text/plain");
        msg.setFrom(new InternetAddress(adminAddress));
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(adminAddress));

        Transport.send(msg);

        return FormValidation.ok("Email was successfully sent");
      } catch (MessagingException e) {
        return FormValidation.errorWithMarkup(
            "<p>Failed to send out e-mail</p><pre>"
                + Util.escape(Functions.printThrowable(e))
                + "</pre>");
      }
    }
  public void sendEmail(final String to, final String subject, final String body)
      throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    switch (protocol) {
      case SMTPS:
        props.put("mail.smtp.ssl.enable", true);
        break;
      case TLS:
        props.put("mail.smtp.starttls.enable", true);
        break;
    }

    Authenticator authenticator = null;
    if (auth) {
      props.put("mail.smtp.auth", true);
      authenticator =
          new Authenticator() {
            private PasswordAuthentication pa = new PasswordAuthentication(username, password);

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

    Session session = Session.getInstance(props, authenticator);
    session.setDebug(debug);

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    InternetAddress[] address = {new InternetAddress(to)};
    message.setRecipients(Message.RecipientType.TO, address);
    message.setSubject(subject);
    message.setSentDate(new Date());
    message.setText(body);
    Transport.send(message);
  }