javamail 簡單例子

     /**
        * "send" method to send the message.
        */
      public static void send(String smtpServer, String to, String cc, String from
       , String subject, String body,String userName,String password)
      {
        try
        {
          Properties props = System.getProperties();
          // -- Attaching to default Session, or we could start a new one --
          props.setProperty("mail.smtp.host", smtpServer);
          props.put("mail.smtp.auth", "true");
          props.put("mail.smtp.starttls.enable","true");
          Session session = Session.getDefaultInstance(props, null);
          // -- Create a new message --
          Message msg = new MimeMessage(session);
          // -- Set the FROM and TO fields --
          msg.setFrom(new InternetAddress(from));
          msg.setHeader("X-Priority","1");
          msg.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to, false));
          if(cc!=null && cc.trim().length()>0){
          msg.setRecipients(Message.RecipientType.CC,
                  InternetAddress.parse(cc, false));
          }
          msg.setSubject(subject);
          msg.setContent(body,"text/html");
          // -- Set some other header information --
          msg.setSentDate(new Date());
          msg.saveChanges();
          // -- Send the message --
          Transport transport = session.getTransport("smtp");
          transport.connect(smtpServer, userName, password);
          transport.sendMessage(msg, msg.getAllRecipients());
          transport.close();

        }
        catch (Exception ex)
        {
          ex.printStackTrace();
        }
      }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章