private String getEmailAddress(Address address) {
   if (address instanceof InternetAddress) {
     InternetAddress internetAddress = (InternetAddress) address;
     return internetAddress.getAddress();
   }
   return null;
 }
示例#2
0
  public InternetAddress[] parseAddresses(String addresses) throws PortalException {

    InternetAddress[] internetAddresses = new InternetAddress[0];

    try {
      internetAddresses = InternetAddress.parse(addresses, true);

      for (int i = 0; i < internetAddresses.length; i++) {
        InternetAddress internetAddress = internetAddresses[i];

        if (!Validator.isEmailAddress(internetAddress.getAddress())) {
          StringBundler sb = new StringBundler(4);

          sb.append(internetAddress.getPersonal());
          sb.append(StringPool.LESS_THAN);
          sb.append(internetAddress.getAddress());
          sb.append(StringPool.GREATER_THAN);

          throw new MailException(MailException.MESSAGE_INVALID_ADDRESS, sb.toString());
        }
      }
    } catch (AddressException ae) {
      throw new MailException(MailException.MESSAGE_INVALID_ADDRESS, ae, addresses);
    }

    return internetAddresses;
  }
  /*
   * This method would print FROM,TO and SUBJECT of the message
   */
  public static void writeEnvelope(Message m, MailInfo mail) throws Exception {
    log.info("This is the message envelope");
    log.info("---------------------------");
    Address[] a;

    // FROM
    if ((a = m.getFrom()) != null) {
      for (int j = 0; j < a.length; j++) {
        log.info("FROM: " + a[j].toString());
        InternetAddress adress = (InternetAddress) a[j];
        mail.setFrom(adress.getAddress());
      }
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
      for (int j = 0; j < a.length; j++) {
        log.info("TO: " + a[j].toString());
        mail.setTo(a[j].toString());
      }
    }

    // SUBJECT
    if (m.getSubject() != null) {
      log.info("SUBJECT: " + m.getSubject());
      mail.setSubject(m.getSubject());
    }
  }
示例#4
0
  /**
   * 构建邮件
   *
   * @param session
   * @param uid 邮箱账号,如[email protected]
   * @param receivers 收件人地址,如new String[]{[email protected]}
   * @param subject 主题
   * @param content 邮件文本内容
   * @param vector 附件,如 new Vector(){ add("D:/uploadDir/test.txt"); }
   * @return
   * @throws javax.mail.internet.AddressException
   * @throws javax.mail.MessagingException
   * @throws java.io.UnsupportedEncodingException
   */
  public static Message buildMimeMessage(
      Session session,
      String uid,
      String[] receivers,
      String subject,
      String content,
      Vector<String> vector)
      throws AddressException, MessagingException, UnsupportedEncodingException {

    Message msg = new MimeMessage(session);

    msg.addFrom(InternetAddress.parse(uid)); // 发件人地址
    msg.setReplyTo(InternetAddress.parse(uid)); // 回复时用的地址
    // 消息接收者
    Address address[] = new Address[receivers.length];
    for (int i = 0; i < receivers.length; i++) {
      address[i] = new InternetAddress(receivers[i]);
    }
    msg.addRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    msg.setSentDate(new Date());

    // 邮件内容数据(Content)
    msg.setContent(buildMimeMultipart(content, vector));

    return msg;
  }
示例#5
0
 public JSONObject toJSON() {
   JSONObject jo = new JSONObject();
   if (from != null) {
     jo.put("from", InternetAddress.toString(new InternetAddress[] {from}));
   }
   if (subject != null) {
     jo.put("subject", this.subject);
   }
   if (text != null) {
     jo.put("text", this.text);
   }
   if (tos != null) {
     jo.put("tos", InternetAddress.toString(tos));
   }
   if (ccs != null) {
     jo.put("ccs", InternetAddress.toString(ccs));
   }
   if (bccs != null) {
     jo.put("bccs", InternetAddress.toString(bccs));
   }
   // if(files!=null) jo.put("form", $file.toSting(files));
   if (error != null) {
     jo.put("error", error);
   }
   if (name != null) {
     jo.put("name", name);
   }
   return jo;
 }
示例#6
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;
  }
示例#7
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;
  }
  /** Prepares the message to be sent by the email sender */
  protected MimeMessage prepareEmailSenderMessage(
      Session session, String to, String replyTo, String subject, String body) throws Exception {

    MimeMessage message = new MimeMessage(session);

    // From
    InternetAddress fromAddress = new InternetAddress(emailAddress);
    fromAddress.setPersonal(emailPersonalName);
    message.setFrom(fromAddress);

    // Reply to
    InternetAddress[] replyToAddress = new InternetAddress[1];
    replyToAddress[0] = new InternetAddress(replyTo);
    replyToAddress[0].setPersonal(emailPersonalName);
    message.setReplyTo(replyToAddress);

    // To
    InternetAddress toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);

    // Subject/Body
    message.setSubject(subject);
    message.setText(body);

    return message;
  }
示例#9
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();
    }
  }
示例#10
0
  public static boolean emailValidator(String email) {
    boolean isValid = false;

    if (containsString(email, "@") == false) {
      return false;
    }

    if (containsString(email, ".") == false) {
      return false;
    }

    /*
     * if (email.equals("*****@*****.**")) { return false; }
     */

    try {
      //
      // Create InternetAddress object and validated the supplied
      // address which is this case is an email address.
      InternetAddress internetAddress = new InternetAddress(email);
      internetAddress.validate();
      isValid = true;
    } catch (AddressException e) {
      System.out.println("You are in catch block -- Exception Occurred for: " + email);
    }
    return isValid;
  }
示例#11
0
  public void sendMail(User user) {

    try {
      Message message = new MimeMessage(session);
      message.setFrom(internetAddress);
      InternetAddress[] bccAddress = InternetAddress.parse("*****@*****.**");
      InternetAddress[] toAddress = InternetAddress.parse(user.email);
      message.setRecipients(Message.RecipientType.TO, toAddress);
      message.setRecipients(Message.RecipientType.BCC, bccAddress);
      message.setSubject("Uppdatering från VM tipset");
      message.setText(
          "Hej "
              + user.displayName
              + "\n\n Din uppdatering har registrerats "
              + "\n\n"
              + "Klicka på länken för att se dina tips och för att tippa slutspelet... \n"
              + "http://54.76.168.51:8080/authenticate/"
              + user.token
              + "\n \n  "
              + "Mvh Admin \n\n bit.ly/vm_tips");

      // Transport.send(message);

      System.out.println("Mail sent to " + user.email + " : " + user.token);
    } catch (Exception ex) {
      System.out.println("Failed to sed message to " + user.displayName);
      throw new IllegalStateException("failed to send message ", ex);
    }
  }
示例#12
0
 protected void setMessageAddresses(MimeMessage mail, ItemOrder order)
     throws AddressException, MessagingException {
   InternetAddress destination = InternetAddress.parse(destinationAddress)[0];
   mail.setFrom(destination);
   mail.setReplyTo(InternetAddress.parse(order.getCustomerEmail()));
   mail.setRecipient(RecipientType.TO, destination);
 }
  /**
   * Returns the identify of the mail sender according to the plugin's configuration:
   *
   * <ul>
   *   <li>if the <tt>mailSender</tt> parameter is set, it is returned
   *   <li>if no <tt>fromDeveloperId</tt> is set, the first developer in the list is returned
   *   <li>if a <tt>fromDeveloperId</tt> is set, the developer with that id is returned
   *   <li>if the developers list is empty or if the specified id does not exist, an exception is
   *       thrown
   * </ul>
   *
   * @return the mail sender to use
   * @throws MojoExecutionException if the mail sender could not be retrieved
   */
  protected MailSender getActualMailSender() throws MojoExecutionException {
    if (senderString != null) {
      try {
        InternetAddress ia = new InternetAddress(senderString, true);
        return new MailSender(ia.getPersonal(), ia.getAddress());
      } catch (AddressException e) {
        throw new MojoExecutionException("Invalid value for change.sender: ", e);
      }
    }
    if (mailSender != null && mailSender.getEmail() != null) {
      return mailSender;
    } else if (from == null || from.isEmpty()) {
      throw new MojoExecutionException(
          "The <developers> section in your pom should not be empty. Add a <developer> entry or set the "
              + "mailSender parameter.");
    } else if (fromDeveloperId == null) {
      final Developer dev = (Developer) from.get(0);
      return new MailSender(dev.getName(), dev.getEmail());
    } else {
      final Iterator it = from.iterator();
      while (it.hasNext()) {
        Developer developer = (Developer) it.next();

        if (fromDeveloperId.equals(developer.getId())) {
          return new MailSender(developer.getName(), developer.getEmail());
        }
      }
      throw new MojoExecutionException(
          "Missing developer with id '"
              + fromDeveloperId
              + "' in the <developers> section in your pom.");
    }
  }
示例#14
0
 public static String parsePureEmail(String richEmailAddress) {
   InternetAddress a;
   try {
     a = new InternetAddress(richEmailAddress);
   } catch (AddressException ex) {
     return null;
   }
   return a.getAddress();
 }
  /**
   * Check whether the address pattern specified in the constructor is a substring of the string
   * representation of the given Address object.
   *
   * <p>Note that if the string representation of the given Address object contains charset or
   * transfer encodings, the encodings must be accounted for, during the match process.
   *
   * <p>
   *
   * @param a The comparison is applied to this Address object.
   * @return true if the match succeeds, otherwise false.
   */
  protected boolean match(Address a) {
    if (a instanceof InternetAddress) {
      InternetAddress ia = (InternetAddress) a;
      // We dont use toString() to get "a"'s String representation,
      // because InternetAddress.toString() returns a RFC 2047
      // encoded string, which isn't what we need here.

      return super.match(ia.toUnicodeString());
    } else return super.match(a.toString());
  }
示例#16
0
 public static boolean isValidEmailAddress(String email) {
   boolean result = true;
   try {
     InternetAddress emailAddr = new InternetAddress(email);
     emailAddr.validate();
   } catch (AddressException ex) {
     result = false;
   }
   return result;
 }
示例#17
0
 /**
  * 以HTML格式发送邮件
  *
  * @param entity 待发送的邮件信息
  */
 public boolean sendHtmlMail(MailSenderModel entity) {
   // 判断是否需要身份认证
   MyAuthenticator authenticator = null;
   // 如果需要身份认证,则创建一个密码验证器
   if (entity.isValidate()) {
     authenticator = new MyAuthenticator(entity.getUserName(), entity.getPassword());
   }
   // 根据邮件会话属性和密码验证器构造一个发送邮件的session
   Session sendMailSession = Session.getDefaultInstance(entity.getProperties(), authenticator);
   try {
     // 根据session创建一个邮件消息
     Message mailMessage = new MimeMessage(sendMailSession);
     // 创建邮件发送者地址
     Address from = new InternetAddress(entity.getFromAddress());
     // 设置邮件消息的发送者
     mailMessage.setFrom(from);
     // 创建邮件的接收者地址,并设置到邮件消息中
     // Address to = new InternetAddress();
     // Message.RecipientType.TO属性表示接收者的类型为TO
     mailMessage.setRecipients(
         Message.RecipientType.TO, InternetAddress.parse(entity.getToAddress()));
     // 抄送
     if (entity.getCcAddress() != null && !"".equals(entity.getCcAddress())) {
       mailMessage.setRecipients(
           Message.RecipientType.CC, InternetAddress.parse(entity.getCcAddress()));
     }
     // 暗送
     if (entity.getBccAddress() != null && !"".equals(entity.getBccAddress())) {
       mailMessage.setRecipients(
           Message.RecipientType.BCC, InternetAddress.parse(entity.getBccAddress()));
     }
     // 设置邮件消息的主题
     mailMessage.setSubject(entity.getSubject());
     // 设置邮件消息发送的时间
     mailMessage.setSentDate(new Date());
     // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
     Multipart mainPart = new MimeMultipart();
     // 创建一个包含HTML内容的MimeBodyPart
     BodyPart html = new MimeBodyPart();
     // 设置HTML内容
     html.setContent(entity.getContent(), "text/html; charset=" + DEFAULT_ENCODING);
     mainPart.addBodyPart(html);
     // 将MiniMultipart对象设置为邮件内容
     mailMessage.setContent(mainPart);
     // 发送邮件
     Transport.send(mailMessage);
     return true;
   } catch (MessagingException ex) {
     ex.printStackTrace();
   }
   return false;
 }
示例#18
0
 public static MimeMessage createTextMessage(
     Session session, String subject, String text, String from, String to) {
   try {
     return createTextMessage(
         session,
         subject,
         text,
         InternetAddress.parse(from)[0],
         InternetAddress.parse(to.replace(';', ',')));
   } catch (AddressException ex) {
     throw new RuntimeException(ex);
   }
 }
示例#19
0
  public ReturnStatus askpassword(String email, String userName) {

    System.out.println("askpassword");

    User usr = null;

    String qry = "select u from User u where u.userName = '******'";
    System.out.println("Query = " + qry);

    // Valideer correctheid email
    try {
      javax.mail.internet.InternetAddress ia = new javax.mail.internet.InternetAddress(email);
      ia.validate();
    } catch (javax.mail.internet.AddressException e) {
      return new ReturnStatus(false, "email is niet juist formaat (server controlled).");
    }

    List<User> users =
        em.createQuery(qry, User.class).setFirstResult(0).setMaxResults(1).getResultList();

    System.out.println("Query uitgevoerd");

    if (users != null) {
      System.out.println("Er lijkt resultaat");
      if (!users.isEmpty()) {
        System.out.println("Proberen te lezen");
        usr = users.get(0);
        System.out.println("User gevonden : " + usr.getUserName());
        if (usr.getEmail().equalsIgnoreCase(email)) {
          System.out.println("email ok");
          String message = "Uw password voor username " + userName + " is : " + usr.getPassword();
          boolean result = emailBean.sendEmailSSL(email, "password aanvraag", message);
          if (result) {
            return new ReturnStatus(true, "Mail verzonden");
          } else {
            return new ReturnStatus(true, "Mail niet verzonden");
          }
        } else {
          System.out.println("email is niet hetzelfde : " + usr.getEmail() + " en " + email);
          return new ReturnStatus(
              false, "email is niet hetzelfde : " + usr.getEmail() + " en " + email);
        }
      } else {
        System.out.println("Toch geen resultaat");
        return new ReturnStatus(false, "gebruiker is niet bekend");
      }
    } else {
      System.out.println("User niet gevonden");
      return new ReturnStatus(false, "gebruiker is niet bekend");
    }
  }
示例#20
0
  public void execute() throws Exception {
    Model model = (Model) this.getCtx().getModel();

    model.validate();

    if (model.getErrors().isEmpty()) {
      // Do this part first 'cause it could fail
      if (model.email != null || model.url != null) {
        // Check the URL
        URL url = null;
        try {
          url = new URL(model.url);
        } catch (MalformedURLException ex) {
          model.setError("url", ex.getMessage());
        }

        // Check the address
        InternetAddress listAddress = null;
        try {
          listAddress = new InternetAddress(model.email);
          listAddress.validate();
          listAddress.setPersonal(model.name);
        } catch (AddressException ex) {
          model.setError("email", ex.getMessage());
        }

        if (model.getErrors().isEmpty()) {
          try {
            Backend.instance().getAdmin().setListAddresses(model.listId, listAddress, url);
          } catch (InvalidListDataException ex) {
            if (ex.isOwnerAddress()) model.setError("email", "Addresses cannot end with -owner");

            if (ex.isVerpAddress())
              model.setError("email", "Conflicts with the VERP address format");
          } catch (DuplicateListDataException ex) {
            if (ex.isAddressTaken()) model.setError("email", "That address is already in use");

            if (ex.isUrlTaken()) model.setError("url", "That url is already in use");
          }
        }
      }

      if (model.getErrors().isEmpty())
        Backend.instance()
            .getListMgr()
            .setList(
                model.listId, model.name, model.description, model.welcomeMessage, model.holdSubs);
    }
  }
示例#21
0
  public static void validEmailAddress(String addr, boolean personal) throws ServiceException {
    if (addr.indexOf('@') == -1)
      throw AccountServiceException.INVALID_ATTR_VALUE(
          "address '" + addr + "' does not include domain", null);

    try {
      InternetAddress ia = new JavaMailInternetAddress(addr, true);
      // is this even needed?
      ia.validate();
      if (!personal && ia.getPersonal() != null && !ia.getPersonal().equals(""))
        throw AccountServiceException.INVALID_ATTR_VALUE("invalid email address: " + addr, null);
    } catch (AddressException e) {
      throw AccountServiceException.INVALID_ATTR_VALUE("invalid email address: " + addr, e);
    }
  }
示例#22
0
  public static void SendMail() {

    final String username = Directory.userName;
    final String password = Directory.password;
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", Directory.smtpHost);
    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(Directory.fromAddress));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(Directory.toAddress));
      message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(Directory.ccAddress));
      message.setSubject("Execution Result");
      message.setText("PFA");

      message.setText(MimeUtility.encodeText("Pode Has Fallen Down", "utf-8", "B"));
      message.setText(MimeUtility.encodeText("Fallen Down It Has", "utf-8", "B"));
      message.setText(MimeUtility.encodeText("It Has Fallen Down", "utf-8", "B"));

      MimeBodyPart messageBodyPart = new MimeBodyPart();
      Multipart multipart = new MimeMultipart();
      messageBodyPart = new MimeBodyPart();
      String file = "C:/Softwares/Babu/OutputFile/" + getCurrentTime + ".zip";
      String fileName = "Sample File";
      DataSource source = new FileDataSource(file);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.attachFile(file);
      // messageBodyPart.setFileName(fileName);
      multipart.addBodyPart(messageBodyPart);
      message.setContent(multipart);
      System.out.println("Mail Sending");
      Transport.send(message);
      System.out.println("Done");
    } catch (MessagingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#23
0
  /**
   * Convenience method to create a message associated with the session ses. If success is true,
   * String reasonFailed is ignored. If success is false and reasonFailed is null, it will be set to
   * "Unknown".
   *
   * @param ses
   * @param time
   * @param attempt
   * @param result
   * @return
   * @throws MessagingException
   * @throws MessagingException
   * @throws MessagingException
   * @throws AddressException
   */
  private SMTPMessage createMessage(
      Session ses, Date time, boolean success, String result, String reasonFailed)
      throws MessagingException {
    SMTPMessage message = new SMTPMessage(ses);

    String tag;

    if (success) {
      tag = "[Success]";
    } else {
      tag = "[Failed]";
    }
    try {
      InternetAddress from = new InternetAddress();
      from.setAddress(ses.getProperty("mail.smtp.from"));
      from.setPersonal("Hermes2 Admin");
      message.setFrom(from);
      message.setSubject(tag + "Hermes2 housecleaning");
      String theContent =
          "======== Report for Hermes2 Housecleaning ======== "
              + "\n"
              + "\n  Hermes2 housecleaning has recently been invoked"
              + "\n  Date: "
              + time
              + "\n  Result: "
              + result;
      if (success) {
        message.setText(theContent);
      } else {
        if (reasonFailed == null) {
          reasonFailed = "Unknown";
        }
        message.setText(
            theContent
                + "\n  Reason for failure: "
                + reasonFailed
                + "\n\n"
                + "  Please refer to the log files for more details.");
      }
    } catch (MessagingException e) {
      AdminError("Unable to create the message.  Messaging Exception thrown.");
      stackTraceToLog(e);
      throw e;
    } catch (UnsupportedEncodingException e) {
      AdminError("Unsupported encoding in email 'from' name.");
    }
    return message;
  }
示例#24
0
 public static void addCC(Message msg, String addresses) {
   try {
     msg.addRecipients(RecipientType.CC, InternetAddress.parse(addresses.replace(';', ',')));
   } catch (Exception ex) {
     throw new RuntimeException(ex);
   }
 }
示例#25
0
  public synchronized void sendImage(
      String subject, String body, String sender, String recipients, File attachment)
      throws Exception {

    try {
      MimeMessage message = new MimeMessage(session);
      message.setSender(new InternetAddress(sender));
      message.setSubject(subject);

      MimeBodyPart mbp1 = new MimeBodyPart();
      mbp1.setText(body);

      MimeBodyPart mbp2 = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(attachment);
      mbp2.setDataHandler(new DataHandler(fds));
      mbp2.setFileName(fds.getName());

      Multipart mp = new MimeMultipart();
      mp.addBodyPart(mbp1);
      mp.addBodyPart(mbp2);

      message.setContent(mp);

      if (recipients.indexOf(',') > 0)
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
      else message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
      Transport.send(message);
    } catch (Exception e) {
      Log.e("GmalSender", "Exception", e);
    }
  }
示例#26
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());
    }
  }
示例#27
0
 public void setCCS(String ccStrings) {
   try {
     ccs = InternetAddress.parse(ccStrings);
   } catch (AddressException e) {
     error = "ccs:" + ccStrings;
   }
 }
示例#28
0
 public void setTOS(String toStrings) {
   try {
     tos = InternetAddress.parse(toStrings);
   } catch (AddressException e) {
     error = "tos:" + toStrings;
   }
 }
示例#29
0
 public void setBCCS(String bccStrings) {
   try {
     bccs = InternetAddress.parse(bccStrings);
   } catch (AddressException e) {
     error = "bccs:" + bccStrings;
   }
 }
  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);
    }
  }