Beispiel #1
0
 @Override
 public void sendEmail(String id, String total, String email) {
   Properties prop = new Properties();
   prop.setProperty("mail.transport.protocol", "smtp");
   Message message = null;
   Transport transport = null;
   Session session = null;
   try {
     session = Session.getDefaultInstance(prop);
     session.setDebug(true);
     // 创建一封新有邮件
     message = (Message) new MimeMessage(session);
     // 标题、正文内容、发件人地址
     message.setSubject("订单支付成功邮件(系统邮件)");
     message.setContent("订单编号为:" + id + ",金额 为: " + total + ",已经支付成功!", "text/html;charset=utf-8");
     message.setFrom(new InternetAddress("*****@*****.**"));
     // 设置用户名密码,收件人地址,发送邮件
     transport = session.getTransport();
     // 通过用户名与密码, 链接邮件服务器
     transport.connect("smtp.sina.com", "soft03_test", "soft03_test");
     transport.sendMessage(message, new Address[] {new InternetAddress(email)});
   } catch (Exception e) {
     throw new RuntimeException(e);
   } finally {
     try {
       // 关闭客户端(释放资源)
       transport.close();
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
 }
Beispiel #2
0
  public static void sendConfirmationRegisterMail(String mail, String name)
      throws UnsupportedEncodingException, MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session =
        Session.getDefaultInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM_ADDRESS, PASSWORD);
              }
            });

    String msgBody = "The staff wish you enjoy the contest!";

    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(FROM_ADDRESS, FROM_NAME));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mail, name));
    msg.setSubject("Welcome to pContest!");
    msg.setText(msgBody);
    Transport.send(msg);
  }
Beispiel #3
0
  public static int removeEmails(Account account, String protocol)
      throws MessagingException, UnknownHostException {
    int count = 0;
    Session session =
        Session.getInstance(
            Protocol.POP3.equals(protocol)
                ? getPop3MailProperties(account)
                : getImapMailProperties(account));
    Folder inbox;

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

    inbox.open(Folder.READ_WRITE);

    count = inbox.getMessageCount();
    for (Message message : inbox.getMessages()) {
      message.setFlag(Flags.Flag.DELETED, true);
    }
    inbox.close(true);
    return count;
  }
Beispiel #4
0
  public boolean send() {

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
      fromAddress = new InternetAddress(from);
      toAddress = new InternetAddress(to);
    } catch (AddressException e) {
      e.printStackTrace();
      return false;
    }

    try {
      simpleMessage.setFrom(fromAddress);
      simpleMessage.setRecipient(RecipientType.TO, toAddress);
      simpleMessage.setSubject(subject);
      simpleMessage.setText(text);

      Transport.send(simpleMessage);
      return true;
    } catch (MessagingException e) {
      e.printStackTrace();
      return false;
    }
  }
  protected void deleteMailsFromUserMailbox(
      final Properties props,
      final String folderName,
      final int start,
      final int deleteCount,
      final String user,
      final String password)
      throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

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

    final int msgCount = f.getMessageCount();

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

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

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();
  }
Beispiel #6
0
  public static void sendMail(String subject, String body) throws IOException, MessagingException {
    final Properties props = new Properties();
    // load a properties file
    props.load(new FileInputStream("mailer.properties"));

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

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

    Transport.send(message);

    System.out.println("mail sent");
  }
  public void postMail(String recipients[], String subject, String message, String from)
      throws MessagingException {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.timeout", 60000);

    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/html");
    Transport.send(msg);
  }
  public static void send(String msg) {
    final String fromEmail = "*****@*****.**";
    final String toEmail = "*****@*****.**";
    final String password = "";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

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

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

    try {

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

      Transport.send(message);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
  // Prefered way of how it should be used.
  public MailAgent(
      String to,
      String cc,
      String bcc,
      String from,
      String subject,
      String content,
      String smtpHost)
      throws FrameworkExecutionException {
    try {
      this.to = to;
      this.cc = cc;
      this.bcc = bcc;
      this.from = from;
      this.subject = subject;
      this.content = content;
      this.smtpHost = smtpHost;

      message = createMessage();
      message.setFrom(new InternetAddress(from));
      setToCcBccRecipients();

      message.setSentDate(new Date());
      message.setSubject(subject);
      message.setText(content);
    } catch (AddressException ex) {
      throw new FrameworkExecutionException(ex);
    } catch (MessagingException ex) {
      throw new FrameworkExecutionException(ex);
    } finally {

    }
  }
Beispiel #10
0
  public WOActionResults createDataStore() throws IOException, MessagingException {
    File emailFile = new File("Resources/largeEmail.eml");
    javax.mail.Message message = convertEmlToMessage(emailFile);

    EOObjectStore osc = new ERXObjectStoreCoordinator(true);
    EOEditingContext ec = ERXEC.newEditingContext(osc);
    ec.lock();
    try {
      DataContainer container =
          (DataContainer)
              EOUtilities.createAndInsertInstance(ec, DataContainer.class.getSimpleName());

      DataStore dataStore =
          (DataStore) EOUtilities.createAndInsertInstance(ec, DataStore.class.getSimpleName());
      dataStore.setDataContainer(container);

      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      message.writeTo(byteStream);
      NSData rawEmail = new NSData(byteStream.toByteArray());
      dataStore.setData(rawEmail);

      ec.saveChanges();
    } finally {
      ec.unlock();
      ec.dispose();
      osc.dispose();
      ec = null;
      osc = null;
    }
    return null;
  }
Beispiel #11
0
  /** Sends Emails to Customers who have not submitted their Bears */
  public static void BearEmailSendMessage(String msgsubject, String msgText, String msgTo) {
    try {
      BearFrom = props.getProperty("BEARFROM");
      // To = props.getProperty("TO");
      SMTPHost = props.getProperty("SMTPHOST");
      Properties mailprops = new Properties();
      mailprops.put("mail.smtp.host", SMTPHost);

      // create some properties and get the default Session
      Session session = Session.getDefaultInstance(mailprops, null);

      // create a message
      Message msg = new MimeMessage(session);

      // set the from
      InternetAddress from = new InternetAddress(BearFrom);
      msg.setFrom(from);
      InternetAddress[] address = InternetAddress.parse(msgTo);
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject(msgsubject);
      msg.setContent(msgText, "text/plain");
      Transport.send(msg);
    } // end try
    catch (MessagingException mex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    } catch (Exception ex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    }
  } // end BearEmailSendMessage
 public void envioCorreo(String mensaje, String modo) {
   String subject = "";
   String destination = obtenerParametros("destinatario");
   String mailHost = obtenerParametros("mailHost");
   String source = obtenerParametros("origen");
   if (modo.equals("Fallo")) subject = "Aplicaci\363n de Carga y Validaci\363n de datos. ERROR!!";
   else subject = "Aplicacion de Carga y Validaci\363n de datos. MENSAJE INFORMATIVO";
   Properties properties = new Properties();
   properties.put("mail.smtp.host", mailHost);
   properties.put("mail.from", source);
   Session session = Session.getInstance(properties, null);
   try {
     Message message = new MimeMessage(session);
     InternetAddress address[] = {new InternetAddress(destination)};
     message.setRecipients(javax.mail.Message.RecipientType.TO, address);
     message.setFrom(new InternetAddress(source));
     message.setSubject(subject);
     message.setContent(mensaje + "\n", "text/plain");
     Transport transport = session.getTransport(address[0]);
     transport.connect();
     transport.sendMessage(message, address);
   } catch (Exception e1) {
     e1.printStackTrace();
   }
 }
  private Message createMessage() {

    Properties props = new Properties();

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

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

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

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

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

    try {
      message.setFrom(new InternetAddress(MimeUtility.encodeText(name) + "<" + name + ">"));
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return message;
  }
Beispiel #14
0
  public void sendMail(String id, String mail) {
    System.out.println("In de send mail method");
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String msgBody =
        "Dear Beta-SMS user,\n Thank you for submiting a feature/issue request. You can follow the status at http://beta-sms.coralic.nl?TABTOSELECT=tab-todo&ID="
            + id
            + "\n \n Thank you for using Beta-SMS.";

    try {
      System.out.println("Building the email and trying to send it");
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "beta-sms.coralic.nl Beta-SMS"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mail, mail));
      msg.setSubject("Beta-SMS feature/issue request processed.");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (AddressException e) {
      System.err.println(e.getMessage());
    } catch (MessagingException e) {
      System.err.println(e.getMessage());
    } catch (UnsupportedEncodingException e) {
      System.err.println(e.getMessage());
    }
  }
  public static void main(String[] args) throws Exception {

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

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

    Message message = new MimeMessage(session);

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

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

    Transport.send(message);

    log.info("Message was sent");
  }
  public static void passwordResetLinkMail(String email) {
    System.out.println("in password reset link");
    System.out.println("email is " + email);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String msgBody =
        "Dear Employee"
            + "As your request we've sent you a password reset link\n"
            + "Past this link to address-bar or click on this link to reset your password\n"
            + "Link is [http://prodigy-software.appspot.com/passwordResetLink]"
            + "\n"
            + "Regards,\n"
            + "  HR  ";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "HR Manager"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, "Hi prodigy"));
      msg.setSubject("Password Reset Link");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (Exception e) {

    }
  }
Beispiel #17
0
  public void send(String subject, String text, String fromEmail, String toEmail) {
    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
              }
            });

    try {
      Message message = new MimeMessage(session);
      // от кого
      message.setFrom(new InternetAddress(username));
      // кому
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
      // тема сообщения
      message.setSubject(subject);
      // текст
      message.setText(text);

      // отправляем сообщение
      Transport.send(message);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
  public static void leaveApprovedMail(
      String employeeName, String fromDate, String toDate, String email) {

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

    String msgBody =
        "Hi "
            + employeeName.toUpperCase()
            + "In response to your request for leave on date from "
            + fromDate
            + " to "
            + toDate
            + " \n"
            + "the management pleased to inform you that your leave request is approved.\n"
            + "Also, do delegate your daily work responsibilities to your assistants\n"
            + "and subordinates well to ensure a smooth flow of operation in your absence.\n"
            + "For your information, with these approved  days of leave,\n"
            + "We wish you a good rest on your off days.\n"
            + "Regards,\n"
            + "  HR  ";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "HR Manager"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, employeeName));
      msg.setSubject("Leave Request Approved");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (Exception e) {

    }
  }
  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);
    }
  }
  public static void leaveDeclinedMail(String email, String employeeId) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String msgBody =
        "Dear Employee"
            + "This letter is in response to your request for a leave of absence beginning"
            + " through   Although we make every effort"
            + " to accommodate employees with a need for time off, unfortunately,"
            + " your leave request is not approved due to Project deadLine to complete"
            + "If you feel that this decision is made in error or that extenuating circumstances warrant"
            + "further review of your request, please feel free to contact me with more information or"
            + "additional details surrounding your need for leave."
            + "Regards,\n"
            + "  HR  ";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "HR Manager"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, "Hi prodigy"));
      msg.setSubject("Leave Request Declined");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (Exception e) {

    }
  }
Beispiel #21
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());
    }
  }
  /*
   * 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());
    }
  }
 /**
  * Helper method for testing which stores a copy of the message locally as the POP3
  *
  * <p>message will be deleted from the server
  *
  * @param msg the message to store
  * @throws IOException If a failure happens writing the message
  * @throws MessagingException If a failure happens reading the message
  */
 protected void storeMessage(Message msg) throws IOException, MessagingException {
   if (backupEnabled) {
     String filename = msg.getFileName();
     if (filename == null) {
       Address[] from = msg.getFrom();
       if (from != null && from.length > 0) {
         filename =
             from[0] instanceof InternetAddress
                 ? ((InternetAddress) from[0]).getAddress()
                 : from[0].toString();
       } else {
         filename = "(no from address)";
       }
       filename += "[" + UUID.getUUID() + "]";
     }
     filename = FileUtils.prepareWinFilename(filename);
     filename = backupFolder + filename + ".msg";
     if (logger.isDebugEnabled()) {
       logger.debug("Writing message to: " + filename);
     }
     File f = FileUtils.createFile(filename);
     FileOutputStream fos = new FileOutputStream(f);
     msg.writeTo(fos);
   }
 }
 /** Returns the date the message was sent (or received if the sent date is null. */
 public String getDate() throws MessagingException {
   Date date;
   SimpleDateFormat df = new SimpleDateFormat("EE M/d/yy");
   if ((date = message.getSentDate()) != null) return (df.format(date));
   else if ((date = message.getReceivedDate()) != null) return (df.format(date));
   else return "";
 }
 /**
  * There seems to be some variation on pop3 implementation so it may be preferrable to mark
  * messages as seen here and also overload the getMessages method to grab only new messages
  */
 protected void flagMessage(Message message) throws MessagingException {
   if (castConnector().isDeleteReadMessages()) {
     message.setFlag(Flags.Flag.DELETED, true);
   } else {
     message.setFlag(Flags.Flag.SEEN, true);
   }
 }
  /**
   * Erstellt eine DisplayMessageBean, die eine fehlerhafte Mail anzeigt.
   *
   * @param content Fehlerhafte Message
   * @param displayMessage Aktuelle DisplayMessageBean
   * @param displayParts List, in die die DisplayParts einsortiert werden.
   * @param inlineParts Map, in die die InlineParts gepackt werden.
   * @param multiparts Map, in die Multiparts gepackt werden.
   * @param e Exception, die beim Einlesen geflogen ist
   */
  private static void assemblePartsForFaultySourceMessage(
      Message message,
      DisplayMessageModel displayMessage,
      List<Part> displayParts,
      Map inlineParts,
      Map multiparts,
      Exception e)
      throws MessagingException {

    // Alle vielleicht schon ansatzweise gefuellten Collections
    // zuruecksetzen
    displayParts.clear();
    inlineParts.clear();
    multiparts.clear();

    // Part erstellen, der auf das Problem hinweist und den Quelltext
    // anfuegt.
    StringBuffer mt = new StringBuffer("Message faulty!\n\n");
    mt.append("The requested messages is faulty because of this reason:\n");
    mt.append(e.getMessage()).append("\n\n");
    mt.append("This is the faulty source of the requested content:\n\n");
    mt.append(displayMessage.getMessageSource());

    // Info-Text-Message erstellen
    Message infoMessage = new MimeMessage((Session) null);
    infoMessage.setText(mt.toString());

    // Info-Text-Message in die Display-Parts packen
    displayParts.add(infoMessage);
  }
Beispiel #27
0
 public static Set<EmailRecipient> getRecipients(Message.RecipientType type, Message message)
     throws MessagingException {
   HashSet<EmailRecipient> out = new HashSet<EmailRecipient>();
   try {
     if (message.getRecipients(type) != null) {
       for (Address recipient : message.getAllRecipients()) {
         String name = "";
         String address = "";
         if (recipient instanceof InternetAddress) {
           if (((InternetAddress) recipient).getPersonal() != null) {
             name = ((InternetAddress) recipient).getPersonal();
           }
           if (((InternetAddress) recipient).getAddress() != null) {
             address = ((InternetAddress) recipient).getAddress();
           }
           RecipientType newType = RecipientType.TO;
           if (type.equals(Message.RecipientType.CC)) {
             newType = RecipientType.CC;
           } else if (type.equals(Message.RecipientType.BCC)) {
             newType = RecipientType.BCC;
           }
           out.add(new EmailRecipient(address, name, newType));
         }
       }
     }
   } catch (AddressException ex) {
     // Do nothing - illegal formatting in recipient field
   }
   return out;
 }
Beispiel #28
0
  /**
   * Sends an email using the given parameters.
   *
   * @param smtp The SMTP server to send from
   * @param from The from-address
   * @param to The to-address
   * @param subj The subject line
   * @param body The message body
   * @throws MessagingException If the email fails to send
   */
  public static void send(
      final String smtp, final String from, final String to, final String subj, final String body)
      throws MessagingException {
    // Silently quit if we are missing any required email information
    if (smtp == null
        || from == null
        || to == null
        || smtp.isEmpty()
        || from.isEmpty()
        || to.isEmpty()) return;

    // Set the host smtp address
    final Properties mailProps = new Properties();
    mailProps.put("mail.smtp.host", smtp);

    // create some properties and get the default Session
    final Session session = Session.getDefaultInstance(mailProps, null);

    // create a message
    final Message msg = new MimeMessage(session);

    // set the from and to address
    final InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    final InternetAddress addressTo = new InternetAddress(to);
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    // set the subject and body
    msg.setSubject(subj);
    msg.setContent(body, "text/plain");

    // send the email message
    Transport.send(msg);
  }
Beispiel #29
0
  public static void sendSmtpMessage(Session session, Message message, Address[] recipients)
      throws MessagingException {

    // message = cloneMimeMessage(message);
    message.setSentDate(new Date());
    setHeaderFieldValue(message, HEADER_X_MAILER, X_MAILER);
    message.saveChanges();

    LOG.info(
        "Sending message '"
            + message.getSubject()
            + "' from '"
            + Str.format(message.getFrom())
            + "' to '"
            + Str.format(recipients)
            + "'.");

    Transport trans = session.getTransport("smtp");
    Properties properties = session.getProperties();
    trans.connect(
        properties.getProperty("mail.smtp.host"),
        properties.getProperty("mail.smtp.auth.user"),
        properties.getProperty("mail.smtp.auth.password"));
    trans.sendMessage(message, recipients);
    trans.close();
  }
  public static void sendEmail(String title, String message, String email)
      throws MessagingException {

    Properties props = new Properties();
    props.setProperty("mail.smtp.auth", "true"); // 设置访问smtp服务器需要认证
    props.setProperty("mail.transport.protocol", "smtp"); // 设置访问服务器的协议

    Session session = Session.getDefaultInstance(props);
    session.setDebug(true); // 打开debug功能

    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(user)); // 设置发件人,163邮箱要求发件人与登录用户必须一致(必填),其它邮箱不了解
    msg.setText(message); // 设置邮件内容
    msg.setSubject("Test"); // 设置邮件主题

    Transport trans = session.getTransport();
    try {
      trans.connect("smtp.163.com", 25, user, pwd); // 连接邮箱smtp服务器,25为默认端口
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      trans.sendMessage(msg, new Address[] {new InternetAddress(email)}); // 发送邮件
    } catch (Exception e) {
      e.printStackTrace();
    }

    trans.close(); // 关闭连接
  }