发布网友 发布时间:2022-04-15 07:34
共1个回答
热心网友 时间:2022-04-15 09:03
这个需要用到mail.jar和activation.jar。 <%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="../error.jsp" %> <%@ page import="javax.mail.* ,javax.mail.internet.*" %> <%@ page import="javax.activation.* ,java.util.*" %> <% request.setCharacterEncoding("gb2312"); String strHost="smtp.163.com"; int nPort=0; String strUserName="name";// 登陆名 String strPassWord="passwd";//密码 String strFrom="name@163.com";//邮箱 String strMessage="message";//邮件内容 Properties props= new Properties(); props.put("mail.smtp.host",strHost); props.put("mail.smtp.auth","true"); Session MailSession=Session.getDefaultInstance(props,null); MailSession.setDebug(true); //创建一个消息 Message msg=new MimeMessage(MailSession); //发件人 InternetAddress from=new InternetAddress(strFrom); msg.setFrom(from); //目标地址 if(strToList!=null && strToList.length()>0) { InternetAddress[] to= {new InternetAddress(strToList)}; msg.setRecipients(Message.RecipientType.TO,to); } else {throw new Exception("No Recipient!"); } if(strSubject!=null) { msg.setSubject(strSubject); } //msg.setSentDate(new Date()); if(strMessage!=null && strMessage.trim().length()>0) { msg.setText(strMessage); } else {msg.setText("NO message to be sent!"); } msg.saveChanges();//报存更改信息 int nMailPort=-1; if(nPort >0) nMailPort=nPort; Transport transport=MailSession.getTransport("smtp"); transport.connect(strHost,nMailPort,strUserName,strPassWord); transport.sendMessage(msg,msg.getAllRecipients()); transport.close(); out.print("邮件发送成功!"); }catch(AuthenticationFailedException ae) { ae.printStackTrace(); out.print("error"); } catch(SendFailedException sf) {Address[] invalid=sf.getInvalidAddresses(); Address[] valid=sf.getValidSentAddresses(); Address[] unsend=sf.getValidUnsentAddresses(); sf.printStackTrace(); } catch(Exception e) {e.printStackTrace(); } %>