1、邮件服务器
SMTP:(发邮件协议)Simple Message Transfer Protocal 简单消息传输协议,默认端口:25 |
POP3:邮局协议(收件协议).POST Office Protocal 默认端口:110 |
tenlet客户端演示如何发送一封邮箱.
1.前期准备:
a.两个邮箱:
b.查看邮箱的帮助文档,找到163(假设)服务商SMTP和POP服务器的地址
SMTP:smtp.163.com
POP3:pop3.163.com
c.把发邮件的用户名和密码用Base64进行编码
username:rewqjkljkfds
password:dfsjakwerfsd
2.发送过程:
telnet smtp.163.com 25
---------------以下内容为SMTP协议
向服务器打招呼
请求身份认证
rewqjkljkfds
dfsjakwerfsd
mail from:<[email protected]>
rcpt to:<[email protected]>
邮件内容开始标记
邮件的内容必须遵守RFC822文档规范.
aaaa正文
邮件内容结束标记
--------------------------------
Quit 退出 telent.
3.接收邮件过程.
4.RFC822规范:约定邮件的内容.
from:[email protected]  发件人 to:[email protected] 正常收件人 cc:抄送 bcc:;密送 subject:主题 空一行 邮件正文 |
1.JavaMail是JavaEE技术之一,是Java中邮件开发的规范.熟悉API.
2.主要的类和接口(mail.jar包括API规范和相关实现):熟悉官方的文档.
简单:
package com.itheima.bookstore.utils.mail; import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.itheima.bookstore.domain.Customer; /** * 发送邮件类 * @author LISAI */ public class SendMail extends Thread { private String context; private Customer customer; public SendMail(String context,Customer customer){ this.context = context; this.customer = customer; } @Override public void run() { Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", "smtp.163.com"); props.setProperty("mail.smtp.auth", "true"); Session session = Session.getInstance(props); session.setDebug(true); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(Message.RecipientType.TO, customer.getEmail()); message.setSubject("来自黑马网站的激活邮件"); message.setContent("欢迎您成为我们的会员<br/>请点击以下链接激活您的账户<a href='http://localhost:8080/"+context+"/servlet/CustomerController?op=active&username="+customer.getUsername()+"&code="+customer.getCode()+"'>激活</a>本邮件由系统发出,请不要直接回复", "text/html;charset=UTF-8"); message.saveChanges(); Transport ts = session.getTransport(); ts.connect("[email protected]", "a1357924680"); ts.sendMessage(message, message.getAllRecipients()); }catch (Exception e) { throw new RuntimeException("发送邮件失败"); } } }
复杂
package cn.nba.store.utils.mail; import java.io.File; /* * 附件类,只有文件,即附件才文件名 */ public class AttachBean { private String cid; private File file; private String fileName; public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public AttachBean() { } public AttachBean(File file, String fileName) { super(); this.file = file; this.fileName = fileName; } }
package cn.nba.store.utils.mail; import java.util.ArrayList; import java.util.List; /** * 表示邮件类,你需要设置:账户名和密码、收件人、抄送(可选)、暗送(可选)、主题、内容,以及附件(可选) * * 在创建了Mail对象之后 * 可以调用它的setSubject()、setContent(),设置主题和正文 * 也可以调用setFrom()和 addToAddress(),设置发件人,和添加收件人。 * 也可以调用addAttch()添加附件 * 创建AttachBean:new AttachBean(new File("..."), "fileName"); */ public class Mail { private String from;//发件人 private StringBuilder toAddress = new StringBuilder();//收件人 private StringBuilder ccAddress = new StringBuilder();//抄送 private StringBuilder bccAddress = new StringBuilder();//暗送 private String subject;//主题 private String content;//正文 // 附件列表 private List<AttachBean> attachList = new ArrayList<AttachBean>(); public Mail() {} public Mail(String from, String to) { this(from, to, null, null); } public Mail(String from, String to, String subject, String content) { this.from = from; this.toAddress.append(to); this.subject = subject; this.content = content; } /** * 返回发件人 * @return */ public void setFrom(String from) { this.from = from; } /** * 返回发件人 * @return */ public String getFrom() { return from; } /** * 返回主题 */ public String getSubject() { return subject; } /** * 设置主题 */ public void setSubject(String subject) { this.subject = subject; } /** * 获取主题内容 */ public String getContent() { return content; } /** * 设置主题内容 * @param content */ public void setContent(String content) { this.content = content; } /** * 获取收件人 * @return */ public String getToAddress() { return toAddress.toString(); } /** * 获取抄送 * @return */ public String getCcAddress() { return ccAddress.toString(); } /** * 获取暗送 * @return */ public String getBccAddress() { return bccAddress.toString(); } /** * 添加收件人,可以是多个收件人 * @param to */ public void addToAddress(String to) { if(this.toAddress.length() > 0) { this.toAddress.append(","); } this.toAddress.append(to); } /** * 添加抄送人,可以是多个抄送人 * @param cc */ public void addCcAddress(String cc) { if(this.ccAddress.length() > 0) { this.ccAddress.append(","); } this.ccAddress.append(cc); } /** * 添加暗送人,可以是多个暗送人 * @param bcc */ public void addBccAddress(String bcc) { if(this.bccAddress.length() > 0) { this.bccAddress.append(","); } this.bccAddress.append(bcc); } /** * 添加附件,可以添加多个附件 * @param attachBean */ public void addAttach(AttachBean attachBean) { this.attachList.add(attachBean); } /** * 获取所有附件 * @return */ public List<AttachBean> getAttachs() { return this.attachList; } }
package cn.nba.store.utils.mail; import java.io.IOException; import java.util.List; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; /** * * @author 用来发邮件! */ public class MailUtils { public static Session createSession(String host, final String username, final String password) { Properties prop = new Properties(); prop.setProperty("mail.host", host);// 指定主机 prop.setProperty("mail.smtp.auth", "true");// 指定验证为true // 创建验证器 Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }; // 获取session对象 return Session.getInstance(prop, auth); } /** * 发送指定的邮件 * * @param mail */ public static void send(Session session, final Mail mail) throws MessagingException, IOException { MimeMessage msg = new MimeMessage(session);// 创建邮件对象 msg.setFrom(new InternetAddress(mail.getFrom()));// 设置发件人 msg.addRecipients(RecipientType.TO, mail.getToAddress());// 设置收件人 // 设置抄送 String cc = mail.getCcAddress(); if (!cc.isEmpty()) { msg.addRecipients(RecipientType.CC, cc); } // 设置暗送 String bcc = mail.getBccAddress(); if (!bcc.isEmpty()) { msg.addRecipients(RecipientType.BCC, bcc); } msg.setSubject(mail.getSubject());// 设置主题 MimeMultipart parts = new MimeMultipart();// 创建部件集对象 MimeBodyPart part = new MimeBodyPart();// 创建一个部件 part.setContent(mail.getContent(), "text/html;charset=utf-8");// 设置邮件文本内容 parts.addBodyPart(part);// 把部件添加到部件集中 /////////////////////////////////////////// // 添加附件 List<AttachBean> attachBeanList = mail.getAttachs();// 获取所有附件 if (attachBeanList != null) { for (AttachBean attach : attachBeanList) { MimeBodyPart attachPart = new MimeBodyPart();// 创建一个部件 attachPart.attachFile(attach.getFile());// 设置附件文件 attachPart.setFileName(MimeUtility.encodeText(attach .getFileName()));// 设置附件文件名 String cid = attach.getCid(); if(cid != null) { attachPart.setContentID(cid); } parts.addBodyPart(attachPart); } } msg.setContent(parts);// 给邮件设置内容 Transport.send(msg);// 发邮件 } }
规范网站:www.jcp.org
版本代号:JSR-*****
Servlet3.0的开发软件环境:
JDK:JDK1.6+
Tomcat:Tomcat7.0+
IDE:MyEclipse10.0+
1.web.xml的配置不是必须滴. |
2.Servlet3.0中Servlet,Filter,Listener使用注解方式实现. Servlet: @WebServlet(urlPatterns = { "/servlet/ServletDemo1" }, initParams = { @WebInitParam(name = "encoding" , value = "utf-8"), @WebInitParam(name = "xxx" , value = "yyy-8") })   Filter: @WebFilter (urlPatterns={"*.action"})   Listener @WebListener |
3.Servlet3.0中文件上传的简易方式 @MultipartConfig 说明表单提交是enctype ="multipart/form-data" request.setCharacterEncoding("utf-8"); // String username = request.getParameter("username"); // System.out.println(username); Part part = request.getPart( "photo"); // 截取文件名 String headerValue = part.getHeader("Content-Disposition"); int index = headerValue.indexOf("filename=" ); String fileName = headerValue.substring(index + 10,headerValue.length() - 1); // part.write(this.getServletContext().getRealPath("/files"+"/1.jpg")); part.write(this.getServletContext().getRealPath("/files" +"/" +fileName)); |
4.对web fragments的支持: 第三方插件或者Servlet(框架),无需配置.而能直接使用在Servlet3.0的工程中. |
5.响应的异步支持: @WebServlet(value="/servlet/RegistServlet",asyncSupported=true) AsyncContext ac = request.startAsync();//开启异步 |