利用socket实现邮件发送

  • 格式:doc
  • 大小:109.50 KB
  • 文档页数:18

邮件发送简单示例:package fss.base;import java.util.*;import javax.mail.*;import javax.mail.internet.*;import java.util.Date;import javax.activation.*;import java.io.*;public class Mail{//把本程序所用变量进行定义。

具体在main中对它们赋植。

private MimeMessage mimeMsg; // MIME邮件对象private Session session; // 邮件会话对象private Properties props; // 系统属性private boolean needAuth = false; // smtp是否需要认证private String username = ""; // smtp认证用户名和密码private String password = "";private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成//MimeMessage对象public Mail(String smtp){setSmtpHost(smtp);createMimeMessage();}public void setSmtpHost(String hostName){System.out.println("设置系统属性:mail.smtp.host = " + hostName);if (props == null)props = System.getProperties(); // 获得系统属性对象props.put("mail.smtp.host", hostName); // 设置SMTP主机}public boolean createMimeMessage(){try {System.out.println("准备获取邮件会话对象!");session = Session.getDefaultInstance(props, null); // 获得邮件会话对象}catch (Exception e){System.err.println("获取邮件会话对象时发生错误!" + e);return false;}System.out.println("准备创建MIME邮件对象!");try {mimeMsg = new MimeMessage(session);// 创建MIME邮件对象mp = new MimeMultipart(); // mp 一个multipart对象// Multipart is a container that holds multiple body parts.return true;}catch (Exception e){System.err.println("创建MIME邮件对象失败!" + e);return false;}}public void setNeedAuth(boolean need) {System.out.println("设置smtp身份认证:mail.smtp.auth = " + need); if (props == null)props = System.getProperties();if (need) {props.put("mail.smtp.auth", "true");} else {props.put("mail.smtp.auth", "false");}}public void setNamePass(String name, String pass){System.out.println("程序得到用户名与密码");username = name;password = pass;}/*设置邮件主题*/public boolean setSubject(String mailSubject) {System.out.println("设置邮件主题!");try {mimeMsg.setSubject(mailSubject);return true;}catch (Exception e) {System.err.println("设置邮件主题发生错误!");return false;}}/*设置邮件体*/public boolean setBody(String mailBody){try{System.out.println("设置邮件体格式");BodyPart bp = new MimeBodyPart();bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+ mailBody, "text/html;charset=GB2312");mp.addBodyPart(bp);return true;}catch (Exception e){System.err.println("设置邮件正文时发生错误!" + e);return false;}}/*设置邮件附件*/public boolean addFileAffix(String filename) {System.out.println("增加邮件附件:" + filename);try {BodyPart bp = new MimeBodyPart();FileDataSource fileds = new FileDataSource(filename);bp.setDataHandler(new DataHandler(fileds));bp.setFileName(fileds.getName());mp.addBodyPart(bp);return true;}catch (Exception e) {System.err.println("增加邮件附件:" + filename + "发生错误!" + e);return false;}}/*设置发信人*/public boolean setFrom(String from) {System.out.println("设置发信人!");try {mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人return true;}catch (Exception e){return false;}}/*设置收信人*/public boolean setTo(String to){System.out.println("设置收信人");if (to == null)return false;try{mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress .parse(to));return true;}catch (Exception e){return false;}}public boolean setCopyTo(String copyto){System.out.println("发送附件到");if (copyto == null)return false;try {mimeMsg.setRecipients(,(Address[]) InternetAddress.parse(copyto));return true;}catch (Exception e){return false;}}public boolean sendout(){try{mimeMsg.setContent(mp); //设置信的内容mimeMsg.saveChanges(); //保存System.out.println("正在发送邮件....");Session mailSession = Session.getInstance(props, null);Transport transport = mailSession.getTransport("smtp"); //协议transport.connect((String) props.get("mail.smtp.host"), username,password); //连接到服务器,写如username,passwordtransport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO)); //设置收件人列表,发送// transport.send(mimeMsg);System.out.println("发送邮件成功!");transport.close();return true;}catch (Exception e){System.err.println("邮件发送失败!" + e);return false;}}public static void main(String[] args){String mailbody = " 用户邮件注册测试<font color=red>欢迎光临</font> <a href=\"\">啦ABC</a>";Mail themail = new Mail("");themail.setNeedAuth(true);if (themail.setSubject("邮件测试") == false)return;//邮件内容支持html 如<font color=red>欢迎光临</font> <a href=\"\">啦ABC</a>if (themail.setBody(mailbody) == false)return;//收件人邮箱if (themail.setTo("shengshuai@") == false)return;//发件人邮箱if (themail.setFrom("shengshuai@") == false) return;//设置附件//if (themail.addFileAffix("#######") == false)//return; // 附件在本地机子上的绝对路径themail.setNamePass("用户名", "密码"); // 用户名与密码if (themail.sendout() == false)return;}}1.import java.io.*;2.import java.text.*;3.import java.util.*;4.import javax.mail.*;5.import javax.mail.internet.*;6.7./**8.* 有一封邮件就需要建立一个ReciveMail对象9.*/10.public class ReciveOneMail {11. private MimeMessage mimeMessage = null;12. private String saveAttachPath = ""; //附件下载后的存放目录13. private StringBuffer bodytext = new StringBuffer();//存放邮件内容14. private String dateformat = "yy-MM-dd HH:mm"; //默认的日前显示格式15.16. public ReciveOneMail(MimeMessage mimeMessage) {17. this.mimeMessage = mimeMessage;18. }19.20. public void setMimeMessage(MimeMessage mimeMessage){21. this.mimeMessage = mimeMessage;22. }23.24. /**25. * 获得发件人的地址和姓名26. */27. public String getFrom() throws Exception {28. InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();29. String from = address[0].getAddress();30. if (from == null)31. from = "";32. String personal = address[0].getPersonal();33. if (personal == null)34. personal = "";35. String fromaddr = personal + "<" + from+ ">";36. return fromaddr;37. }38.39. /**40. * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同"to"----收件人"cc"---抄送人地址"bcc"---密送人地址41. */42. public String getMailAddress(String type) throws Exception {43. String mailaddr = "";44. String addtype = type.toUpperCase();45. InternetAddress[] address = null;46. if (addtype.equals("TO") || addtype.equals("CC")|| addtype.equals("BCC")) {47. if (addtype.equals("TO")) {48. address = (InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.TO);49. } else if (addtype.equals("CC")) {50. address = (InternetAddress[])mimeMessage.getRecipients();51. } else {52. address = (InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.BCC);53. }54. if (address != null) {55. for (int i = 0; i < address.length; i++) {56. String email = address[i].getAddress();57. if (email == null)58. email = "";59. else {60. email = MimeUtility.decodeText(email);61. }62. String personal = address[i].getPersonal();63. if (personal == null)64. personal = "";65. else {66. personal = MimeUtility.decodeText(personal);67. }68. String compositeto =personal + "<" + email + ">";69. mailaddr += "," + compositeto;70. }71. mailaddr = mailaddr.substring(1);72. }73. } else {74. throw new Exception("Error emailaddrtype!");75. }76. return mailaddr;77. }78.79. /**80. * 获得邮件主题81. */82. public String getSubject() throws MessagingException {83. String subject = "";84. try {85. subject = MimeUtility.decodeText(mimeMessage.getSubject());86. if (subject == null)87. subject = "";88. } catch (Exception exce) {}89. return subject;90. }91.92. /**93. * 获得邮件发送日期94. */95. public String getSentDate() throws Exception {96. Date sentdate = mimeMessage.getSentDate();97. SimpleDateFormat format = new SimpleDateFormat(dateformat);98. return format.format(sentdate);99. }100.101./**102.* 获得邮件正文内容103.*/104.public String getBodyText() {105.return bodytext.toString();106.}107.108./**109.* 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件主要是根据MimeType类型的不同执行不同的操作,一步一步的解析110.*/111.public void getMailContent(Part part) throws Exception {112.String contenttype = part.getContentTyp e();113.int nameindex = contenttype.indexOf("na me");114.boolean conname = false;115.if (nameindex != -1)116.conname = true;117.System.out.println("CONTENTTYPE: " + co ntenttype);118.if (part.isMimeType("text/plain") && !c onname) {119.bodytext.append((String) part.get Content());120.} else if (part.isMimeType("text/html") && !conname) {121.bodytext.append((String) part.get Content());122.} else if (part.isMimeType("multipart/* ")) {123.Multipart multipart = (Multipar t) part.getContent();124.int counts = multipart.getCount ();125.for (int i = 0; i < counts;i++) {126.getMailContent(multipart.g etBodyPart(i));127.}128.} else if (part.isMimeType("message/rfc 822")) {129.getMailContent((Part) part.getCon tent());130.} else {}131.}132.133./**134.* 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"135.*/136.public boolean getReplySign() throws Messaging Exception {137.boolean replysign = false;138.String needreply[] = mimeMessage 139..getHeader("Disposition-No tification-To");140.if (needreply != null) {141.replysign = true;142.}143.return replysign;144.}145.146./**147.* 获得此邮件的Message-ID148.*/149.public String getMessageId() throws MessagingE xception {150.return mimeMessage.getMessageID(); 151.}152.153./**154.* 【判断此邮件是否已读,如果未读返回返回false,反之返回true】155.*/156.public boolean isNew() throws MessagingExcepti on {157.boolean isnew = false;158.Flags flags = ((Message) mimeMessage).getFlags();159.Flags.Flag[] flag = flags.getSystemFlag s();160.System.out.println("flags's length: " + flag.length);161.for (int i = 0; i < flag.length; i ++) {162.if (flag[i] == Flags.Flag.SEEN) {163.isnew = true;164.System.out.println("seen Message.......");165.break;166.}167.}168.return isnew;169.}170.171./**172.* 判断此邮件是否包含附件173.*/174.public boolean isContainAttach(Part part) thro ws Exception {175.boolean attachflag = false;176.String contentType = part.getContentTyp e();177.if (part.isMimeType("multipart/*")) {178.Multipart mp = (Multipart) par t.getContent();179.for (int i = 0; i < mp.getC ount(); i++) {180.BodyPart mpart = mp.get BodyPart(i);181.String disposition = mp art.getDisposition();182.if ((disposition != nul l)183.&& ((disp osition.equals(Part.ATTACHMENT)) || (disposition184..equals(Part.INLINE))))185.attachflag = tru e;186.else if (mpart.isMimeTyp e("multipart/*")) {187.attachflag = isC ontainAttach((Part) mpart);188.} else {189.String contype = mpart.getContentType();190.if (contype.toLow erCase().indexOf("application") != -1)191.attachflag = true;192.if (contype.toLow erCase().indexOf("name") != -1)193.attachflag = true;194.}195.}196.} else if (part.isMimeType("message/rfc 822")) {197.attachflag = isContainAttach((Pa rt) part.getContent());198.}199.return attachflag;200.}201.202./**203.* 【保存附件】204.*/205.public void saveAttachMent(Part part) throws Exception {206.String fileName = "";207.if (part.isMimeType("multipart/*")) {208.Multipart mp = (Multipart) par t.getContent();209.for (int i = 0; i < mp.getC ount(); i++) {210.BodyPart mpart = mp.get BodyPart(i);211.String disposition = mp art.getDisposition();212.if ((disposition != nul l)213.&& ((disp osition.equals(Part.ATTACHMENT)) || (disposition214..equals(Part.INLINE)))) {215.fileName = mpart .getFileName();216.if (fileName.toLo werCase().indexOf("gb2312") != -1) {217.fileName = MimeUtility.decodeText(fileName);218.}219.saveFile(fileName, mpart.getInputStream());220.} else if (mpart.isMime Type("multipart/*")) {221.saveAttachMent(mpa rt);222.} else {223.fileName = mpart .getFileName();224.if ((fileName != null)225.&& (fileName.toLowerCase().indexOf("GB2312") != -1)) { 226.fileName = MimeUtility.decodeText(fileName);227.saveFile(f ileName, mpart.getInputStream());228.}229.}230.}231.} else if (part.isMimeType("message/rfc 822")) {232.saveAttachMent((Part) part.getCon tent());233.}234.}235.236./**237.* 【设置附件存放路径】238.*/239.240.public void setAttachPath(String attachpath) {241.this.saveAttachPath = attachpath; 242.}243.244./**245.* 【设置日期显示格式】246.*/247.public void setDateFormat(String format) throw s Exception {248.this.dateformat = format;249.}250.251./**252.* 【获得附件存放路径】253.*/254.public String getAttachPath() {255.return saveAttachPath;256.}257.258./**259.* 【真正的保存附件到指定目录里】260.*/261.private void saveFile(String fileName, InputSt ream in) throws Exception {262.String osName = System.getProperty("os.name");263.String storedir = getAttachPath(); 264.String separator = "";265.if (osName == null)266.osName = "";267.if (osName.toLowerCase().indexOf("win") != -1) {268.separator = "\\";269.if (storedir == null || store dir.equals(""))270.storedir = "c:\\tmp"; 271.} else {272.separator = "/";273.storedir = "/tmp";274.}275.File storefile = new File(storedir + separator + fileName);276.System.out.println("storefile's path: "+ storefile.toString());277.// for(int i=0;storefile.exists();i++){278.// storefile = new File(storedir+separ ator+fileName+i);279.// }280.BufferedOutputStream bos = null; 281.BufferedInputStream bis = null;282.try {283.bos = new BufferedOutputStream( new FileOutputStream(storefile));284.bis = new BufferedInputStream(i n);285.int c;286.while ((c = bis.read()) != -1 ) {287.bos.write(c);288.bos.flush();289.}290.} catch (Exception exception) { 291.exception.printStackTrace(); 292.throw new Exception("文件保存失败!");293.} finally {294.bos.close();295.bis.close();296.}297.}298.299./**300.* PraseMimeMessage类测试301.*/302.public static void main(String args[]) throws Exception {303.Properties props = System.getProperties ();304.props.put("mail.smtp.host", " ");305.props.put("mail.smtp.auth", "true"); 306.Session session = Session.getDefaultIns tance(props, null);307.URLName urln = new URLName("pop3", "p ", 110, null,308."xiangzhengyan", "pass");309.Store store = session.getStore(urln);310.store.connect();311.Folder folder = store.getFolder("INBOX");312.folder.open(Folder.READ_ONLY);313.Message message[] = folder.getMessages( );314.System.out.println("Messages's length: "+ message.length);315.ReciveOneMail pmm = null;316.for (int i = 0; i < message.length;i++) {317.System.out.println("============== ========");318.pmm = new ReciveOneMail((MimeMe ssage) message[i]);319.System.out.println("Message " +i + " subject: " + pmm.getSubject());320.System.out.println("Message " +i + " sentdate: "+ pmm.getSentDate());321.System.out.println("Message " +i + " replysign: "+ pmm.getReplySign());322.System.out.println("Message " +i + " hasRead: " + pmm.isNew());323.System.out.println("Message " +i + " containAttachment: "+ pmm.isContainAttach((Part)message[i]));324.System.out.println("Message " +i + " form: " + pmm.getFrom());325.System.out.println("Message " +i + " to: "+ pmm.getMailAddress("to"));326.System.out.println("Message " +i + " cc: "+ pmm.getMailAddress("cc"));327.System.out.println("Message " +i + " bcc: "+ pmm.getMailAddress("bcc"));328.pmm.setDateFormat("yy年MM月dd 日HH:mm");329.System.out.println("Message " +i + " sentdate: "+ pmm.getSentDate());330.System.out.println("Message " +i + " Message-ID: "+ pmm.getMessageId());331.// 获得邮件内容=============== 332.pmm.getMailContent((Part) message[i]);333.System.out.println("Message " +i + " bodycontent: \r\n"334.+ pmm.getBodyText ());335.pmm.setAttachPath("c:\\");336.pmm.saveAttachMent((Part) message[i]);337.}338.}339.}。