整个流程如下:
telnet localhost 25 //telnet 可连接互联网任意一台主机 ehlo flx auth login YWFh MTIz mail from: <[email protected]> rcpt to: <[email protected]> data from: <[email protected]> to: <[email protected]> subject: test 美令,咱们分手吧 中正 . quit telnet localhost 110 user aaa pass 123 stat list retr 2 quit
public class Demo1 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost",25); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); OutputStream out = socket.getOutputStream(); System.out.println(br.readLine()); out.write("ehlo flx\r\n".getBytes()); System.out.println(br.readLine()); System.out.println(br.readLine()); out.write("auth login\r\n".getBytes()); System.out.println(br.readLine()); out.write("YWFh\r\n".getBytes()); System.out.println(br.readLine()); out.write("MTIz\r\n".getBytes()); System.out.println(br.readLine()); out.write("mail from: <[email protected]>\r\n".getBytes()); System.out.println(br.readLine()); out.write("rcpt to: <[email protected]>\r\n".getBytes()); System.out.println(br.readLine()); out.write("data\r\n".getBytes()); System.out.println(br.readLine()); out.write("from:<[email protected]>\r\nto:<[email protected]>\r\nsubject:test\r\n".getBytes()); out.write(".\r\n".getBytes()); System.out.println(br.readLine()); out.write("quit\r\n".getBytes()); System.out.println(br.readLine()); br.close(); out.close(); socket.close(); } }
MIME协议常用头字段
Content-type:字段
Content-Disposition头字段
Content-Disposition: attachment; filename="1.bmp"
Content-ID头字段
Content-ID: it315logo_gif
<img src="cid:it315logo_gif">
MIME协议例:
//创建简单邮件
public class SimpleMail { public static void main(String[] args) throws Exception { Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); message.setSubject("test"); message.setContent("aaaaaaaaaaaa", "text/html"); message.saveChanges(); message.writeTo(new FileOutputStream("c:\\1.eml")); } }
//创建带图片邮件
public class ImageMail { public static void main(String[] args) throws Exception { Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); message.setSubject("test"); //创建邮件中的数据 //创建正文
MimeBodyPart text = new MimeBodyPart(); text.setContent("aaaa<br/><img src='cid:1.jpg'><br/>aaaaaaaa", "text/html"); //创建图片,不需要再setContent,setDataHandler可以感知类型
MimeBodyPart image = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource("src/1.jpg"));//jaf技术,把文件作为流
image.setDataHandler(dh); image.setContentID("1.jpg"); //描述数据之间的关系
MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text); mm.addBodyPart(image); mm.setSubType("related"); message.setContent(mm); message.saveChanges(); message.writeTo(new FileOutputStream("c:\\1.eml")); } }
//创建带附件的邮件
public class AttachMail { public static void main(String[] args) throws Exception { Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); message.setSubject("test"); //创建封装正文数据的bodypart
MimeBodyPart text = new MimeBodyPart(); text.setContent("aaaaaaaaaaaa", "text/html"); //创建封装附件数据的bodypart
MimeBodyPart attach = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource("src/1.mp3")); attach.setDataHandler(dh); attach.setFileName(dh.getName()); //设置附件名 //mixed
MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text); mm.addBodyPart(attach); mm.setSubType("mixed"); message.setContent(mm); message.saveChanges(); message.writeTo(new FileOutputStream("c:\\1.eml")); } }
//创建最复杂邮件
public class ComplexMail { public static void main(String[] args) throws Exception { //创建邮件
Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); message.setSubject("测试"); //创建bodypart封装正文
MimeBodyPart text = new MimeBodyPart(); text.setContent("这是中文邮件a<img src='cid:1.jpg'>", "text/html;charset=UTF-8"); //创建bodypart封装图片
MimeBodyPart image = new MimeBodyPart(); image.setDataHandler(new DataHandler(new FileDataSource("src/1.jpg"))); image.setContentID("1.jpg"); //创建bodypart封装附件,解决乱码
MimeBodyPart attach = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource("src/光辉岁月.mp3")); attach.setDataHandler(dh); attach.setFileName(MimeUtility.encodeText(dh.getName()));//content-disposition //描述数据关系
MimeMultipart content = new MimeMultipart(); content.addBodyPart(text); content.addBodyPart(image); content.setSubType("related");
MimeBodyPart mbp = new MimeBodyPart(); mbp.setContent(content); MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(mbp); mm.addBodyPart(attach); mm.setSubType("mixed"); message.setContent(mm); message.saveChanges(); message.writeTo(new FileOutputStream("c:\\1.eml")); } }
ps:MIME协议已经突破原来的邮件领域广泛用在数据描述协议中,简单的一堆数据,不同类型,传给对方.
使用JavaMail发送一封简单的邮件:
//发送邮件
public class SendMail { public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.smtp.host", "localhost"); prop.setProperty("mail.transport.protocol", "smtp"); prop.setProperty("mail.smtp.auth", "true"); javax.mail.Session session = javax.mail.Session.getInstance(prop); session.setDebug(true);//打印与服务器的交互过程
Message message = createMessage(session); Transport ts = session.getTransport(); ts.connect("aaa", "123"); ts.sendMessage(message,message.getAllRecipients());//获取收件人
ts.close(); } private static Message createMessage(Session session) throws Exception { //创建邮件
MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); message.setSubject("test"); message.setContent("aaaaaaaaaaaa", "text/html"); message.saveChanges(); return message; } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title>注册页面</title></head>
<body>
<form action="${pageContext.request.contextPath }/servlet/RegisterServlet" method="post"> 用户名:<input type="text" name="username"><br/> 密码:<input type="password" name="password"><br/> 电子邮箱:<input type="text" name="email"><br/>
<input type="submit" value="注册">
</form>
</body>
</html>
//用户注册时,发送邮件通知
public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws Exception { String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); User user = new User(); user.setEmail(email); user.setPassword(password); user.setUsername(username); try{ //开启发送邮件线程,如果不开线程的话,如邮件有问题,后续代码无法执行
Thread t = new Thread(new SendMail(user)); t.start(); request.setAttribute("message", "注册成功!!"); }catch (Exception e) { e.printStackTrace(); request.setAttribute("message", "注册失败!!"); } request.getRequestDispatcher("/message.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
public class SendMail implements Runnable { private String host = "localhost"; private String email = "[email protected]"; private String username = "aaa"; private String password = "123"; private User user; public SendMail(User user) { this.user = user; } public void run() { try{ Thread.sleep(1000*30); send(user); }catch (Exception e) { throw new RuntimeException(e); } } public void send(User user) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.host", host); prop.setProperty("mail.transport.protocol", "smtp"); Session session = Session.getInstance(prop); Message message = createmessage(session, user); Transport ts = session.getTransport(); ts.connect(username, password); ts.sendMessage(message, message.getAllRecipients()); ts.close(); } public Message createmessage(Session session,User user) throws Exception{ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(email)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); message.setSubject("xxx网站用户注册邮件"); String content = "恭喜您,注册成功,您注册的用户名:"+ user.getUsername()!!"; message.setContent(content, "text/html;charset=UTF-8"); message.saveChanges(); return message; } }