javamail 简单例子

来源:互联网 发布:java中线程同步的机制 编辑:程序博客网 时间:2024/06/04 19:28

     /**
        * "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();
        }
      }

原创粉丝点击