java发送Email

来源:互联网 发布:二手摩托车交易软件 编辑:程序博客网 时间:2024/05/16 14:03

/**
 发送邮件的方法
 @param mailStr  -  发送的邮件体
**/
 public void sendMail(String mailStr){
       try {
           Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
           final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
           // Get a Properties object
           Properties props = System.getProperties();
           props.setProperty("mail.smtp.host", getHost());
           props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
           props.setProperty("mail.smtp.socketFactory.fallback", "false");
           props.setProperty("mail.smtp.starttls.enable", "true");
           props.setProperty("mail.smtp.startssl.enable", "true");
           props.setProperty("mail.smtp.port", this.getPort());
           props.put("mail.smtp.auth", "true");
           Session session = Session.getDefaultInstance(props, new Authenticator(){
               protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication(userName,password);
               }
           }
           );

           Message msg = new MimeMessage(session);
           msg.setFrom(new InternetAddress(getUserName()));
           msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(queryTosString(),false));
           msg.setSubject(getSubject());
           msg.setText(mailStr);
           msg.setSentDate(new Date());
           Transport.send(msg);
       } catch (Exception ex) {
           throw new RuntimeException("Email send failed!");
       }
 }

原创粉丝点击