欢迎光临
我们一直在努力

Java Mail 例子-JSP教程,邮件相关

建站超值云服务器,限时71元/月

 

  网上很多,不过一般都是没有smtp验证的,下边是一段示例代码:
  不能直接运行的,不过,可以看看里面关于验证的部分。

  //发送邮件函数
  public boolean sendmail(string mailto,string mailsubject,string mailbody){
    //发送email
    try {
      //default account information
      string smtpserver = “smtp.smtpserver.com”;
      string smtpauth = “true”;
      string smtpuser = “username”;
      string smtppassword = “password”;
      string from = “from@yourserver.com“;
      string to = mailto;
      string subject = mailsubject;
      string text = mailbody;
      java.util.resourcebundle resbundle;
      resbundle = java.util.resourcebundle.getbundle(“mailinfo”,
          locale.simplified_chinese);
      if (resbundle != null) {
        smtpserver = resbundle.getstring(“mail.smtp.host”);
        smtpauth = resbundle.getstring(“mail.smtp.auth”);
        smtpuser = resbundle.getstring(“mail.smtp.user”);
        smtppassword = resbundle.getstring(“mail.smtp.password”);
        from = resbundle.getstring(“mail.smtp.from”);
      }
      properties props = new properties();
      session sendmailsession;
      transport transport;
      props.put(“mail.smtp.host”, smtpserver);
      props.put(“mail.smtp.auth”, smtpauth);
      if (“true”.equals(smtpauth)) {
        //smtp服务器需要验证,用myauthertiactor来创建mail session
        myauthenticator myauth = new myauthenticator(smtpuser, smtppassword);
        sendmailsession = session.getinstance(props, myauth);
      }
      else {
        sendmailsession = session.getinstance(props);
      }
      //debug
      sendmailsession.setdebug(true);
      message newmessage = new mimemessage(sendmailsession);
      newmessage.setfrom(new internetaddress(from));
      newmessage.setrecipient(message.recipienttype.to,
                              new internetaddress(mailto));
      newmessage.setsubject(subject);
      newmessage.setsentdate(new date());
      newmessage.settext(text);
      newmessage.savechanges();
      transport = sendmailsession.gettransport(“smtp”);
      transport.send(newmessage, newmessage.getallrecipients());
      transport.close();
    }
    catch (exception mailex) {
      system.err.println(“send mail error:” + mailex.getmessage());
      return false;
    }
    return true;
  }

  //smtp需要验证时候的验证类
  class myauthenticator
      extends javax.mail.authenticator {
    private string struser;
    private string strpwd;
    public myauthenticator(string user, string password) {
      this.struser = user;
      this.strpwd = password;
    }

    protected passwordauthentication getpasswordauthentication() {
      return new passwordauthentication(struser, strpwd);
    }
  }

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » Java Mail 例子-JSP教程,邮件相关
分享到: 更多 (0)