java实现简单发送邮件功能-mile米乐体育
本文实例为大家分享了java实现简单发送邮件的具体代码,供大家参考,具体内容如下
添加依赖
自定义异常类
public class emailexception extends exception { public emailexception(string message) { super(message); } public emailexception() { super(); } /** * */ private static final long serialversionuid = 115631651651651651l; }
imap协议读取邮件
import java.io.bufferedinputstream; import java.io.bufferedoutputstream; import java.io.file; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.unsupportedencodingexception; import java.text.simpledateformat; import java.util.date; import java.util.properties; import javax.mail.address; import javax.mail.bodypart; import javax.mail.flags; import javax.mail.folder; import javax.mail.message; import javax.mail.messagingexception; import javax.mail.multipart; import javax.mail.part; import javax.mail.session; import javax.mail.store; import javax.mail.internet.internetaddress; import javax.mail.internet.mimemessage; import javax.mail.internet.mimemultipart; import javax.mail.internet.mimeutility; import com.sun.mail.util.mailsslsocketfactory; public class imapreceivemail { private string user = "";//账号 private string password = "";//密码 private string host = ""; // smtp服务器 // private properties props = null; private folder folder = null;//收件箱 private store store = null;//实例对象 // final string pop3 = "imap"; final string imap = "imap"; public imapreceivemail(string user,string password) { this.password = password;//密码 this.user = user;//账户 } /** * @param message 邮件对象 * @param to 收件人 * @throws messagingexception * @throws ioexception */ // public void forwardmail(message message,string to) throws messagingexception, ioexception { // message forward = new mimemessage(session); // forward.setsubject(message.getsubject()); // forward.setfrom(new internetaddress(to)); // forward.setrecipient(message.recipienttype.to, new internetaddress(to)); // forward.setsentdate(new date()); // forward.setcontent(message.getcontent(), message.getcontenttype()); // // transport smtp = session.gettransport("smtp"); // smtp.connect(host, user, password);//连接服务器的邮箱 // smtp.sendmessage(forward, forward.getallrecipients()); // smtp.close(); // } /** * 接收邮件 */ public folder resceive() throws exception { /** * 因为现在使用的是163邮箱 而163的 pop地址是 pop3.163.com 端口是 110 比如使用好未来企业邮箱 就需要换成 好未来邮箱的 * pop服务器地址 pop.263.net 和 端口 110 */ string duankou = ""; // 端口号 string servicepath = ""; // 服务器地址 if(user==null||user.length()==0) throw new emailexception("账户不能为空!!!!"); if(password==null||password.length()==0) throw new emailexception("密码不能为空!!!!"); if(user.contains("@163")) { duankou = "143"; // 端口号 servicepath = "imap.163.com"; // 服务器地址 }else if(user.contains("@qq")) { duankou = "993"; // 端口号 servicepath = "imap.qq.com"; // 服务器地址 }else { throw new emailexception("不支持该协议"); } // 准备连接服务器的会话信息 properties props = new properties(); props.setproperty("mail.store.protocol", imap); // 使用pop3协议 props.setproperty("mail.imap.socketfactory.fallback", "false"); props.setproperty("mail.imap.port", duankou); // 端口 props.setproperty("mail.imap.socketfactory.port", duankou); // 端口 props.setproperty("mail.transport.protocol", "smtp");// 发送邮件协议名称 props.setproperty("mail.smtp.auth", "true"); //需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条 props.setproperty("mail.host", host); //关闭读取附件时分批获取 base64 输入流的配置 props.setproperty("mail.imap.partialfetch", "false"); props.setproperty("mail.imaps.partialfetch", "false"); // props.setproperty("mail.pop3.host", servicepath); // pop3服务器 // final string ssl_factory = "javax.net.ssl.sslsocketfactory"; // security.addprovider(new com.sun.net.ssl.internal.ssl.provider()); // props.setproperty("mail.imap.socketfactory.class", ssl_factory); mailsslsocketfactory sf = new mailsslsocketfactory();//ssl加密 sf.settrustallhosts(true); props.put("mail.imap.ssl.enable", "true"); props.put("mail.imap.ssl.socketfactory", sf); // 创建session实例对象 session session = session.getinstance(props); session.setdebug(false); store = session.getstore(imap); store.connect(servicepath,user,password); // 163邮箱程序登录属于第三方登录所以这里的密码是163给的授权密码而并非普通的登录密码 // 获得收件箱 folder = store.getfolder("inbox"); /* * folder.read_only:只读权限 folder.read_write:可读可写(可以修改邮件的状态) */ folder.open(folder.read_write); // 打开收件箱 // 由于pop3协议无法获知邮件的状态,所以getunreadmessagecount得到的是收件箱的邮件总数 // system.out.println("未读邮件数: " folder.getunreadmessagecount()); // 由于pop3协议无法获知邮件的状态,所以下面得到的结果始终都是为0 // system.out.println("删除邮件数: " folder.getdeletedmessagecount()); // system.out.println("新邮件: " folder.getnewmessagecount()); // 获得收件箱中的邮件总数 // system.out.println("邮件总数: " folder.getmessagecount()); // 得到收件箱中的所有邮件,并解析 // message[] messages = folder.getmessages(); // parsemessage(messages); // 得到收件箱中的所有邮件并且删除邮件 // deletemessage(messages); // 释放资源 // folder.close(true); // store.close(); return folder; } public void colsefolder() throws messagingexception {//关闭资源 if(folder!=null) { folder.close(); } if(store!=null) { store.close(); } } /** * 解析邮件 * * @param messages 要解析的邮件列表 */ public void parsemessage(message... messages) throws messagingexception, ioexception { if (messages == null || messages.length < 1) throw new messagingexception("未找到要解析的邮件!"); // 解析所有邮件 for (int i = 0, count = messages.length; i < count; i ) { mimemessage msg = (mimemessage) messages[i]; system.out.println("------------------解析第" msg.getmessagenumber() "封邮件-------------------- "); system.out.println("主题: " getsubject(msg)); system.out.println("发件人: " getfrom(msg)); system.out.println("收件人:" getreceiveaddress(msg, null)); system.out.println("发送时间:" getsentdate(msg, null)); system.out.println("是否已读:" isseen(msg)); system.out.println("邮件优先级:" getpriority(msg)); system.out.println("是否需要回执:" isreplysign(msg)); system.out.println("邮件大小:" msg.getsize() * 1024 "kb"); boolean iscontainerattachment = iscontainattachment(msg); system.out.println("是否包含附件:" iscontainerattachment); if (iscontainerattachment) { saveattachment(msg, "f:\\mailtest\\" msg.getsubject() "_" i "_"); // 保存附件 } stringbuffer content = new stringbuffer(30); getmailtextcontent(msg, content); system.out.println("邮件正文:" (content.length() > 100 ? content.substring(0, 100) "..." : content)); system.out.println("------------------第" msg.getmessagenumber() "封邮件解析结束-------------------- "); system.out.println(); } } /** * 解析邮件 * * @param messages 要解析的邮件列表 */ public void deletemessage(message... messages) throws messagingexception, ioexception { if (messages == null || messages.length < 1) throw new messagingexception("未找到要解析的邮件!"); // 解析所有邮件 for (int i = 0, count = messages.length; i < count; i ) { /** * 邮件删除 */ message message = messages[i]; string subject = message.getsubject(); // set the delete flag to true message.setflag(flags.flag.deleted, true); system.out.println("marked delete for message: " subject); } } /** * 获得邮件主题 * * @param msg 邮件内容 * @return 解码后的邮件主题 */ public string getsubject(mimemessage msg) throws unsupportedencodingexception, messagingexception { return mimeutility.decodetext(msg.getsubject()); } /** * 获得邮件发件人 * * @param msg 邮件内容 * @return 姓名
* message.recipienttype.to 收件人 *
** message.recipienttype.cc 抄送 *
** message.recipienttype.bcc 密送 *
* * @param msg 邮件内容 * @param type 收件人类型 * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ... * @throws messagingexception */ public string getreceiveaddress(mimemessage msg, message.recipienttype type) throws messagingexception { stringbuffer receiveaddress = new stringbuffer(); address[] addresss = null; if (type == null) { addresss = msg.getallrecipients(); } else { addresss = msg.getrecipients(type); } if (addresss == null || addresss.length < 1) throw new messagingexception("没有收件人!"); for (address address : addresss) { internetaddress internetaddress = (internetaddress) address; receiveaddress.append(internetaddress.tounicodestring()).append(","); } receiveaddress.deletecharat(receiveaddress.length() - 1); // 删除最后一个逗号 return receiveaddress.tostring(); } /** * 获得邮件发送时间 * * @param msg 邮件内容 * @return yyyy年mm月dd日 星期x hh:mm * @throws messagingexception */ public string getsentdate(mimemessage msg, string pattern) throws messagingexception { date receiveddate = msg.getsentdate(); if (receiveddate == null) return ""; if (pattern == null || "".equals(pattern)) pattern = "yyyy年mm月dd日 e hh:mm "; return new simpledateformat(pattern).format(receiveddate); } /** * 判断邮件中是否包含附件 * * @param msg 邮件内容 * @return 邮件中存在附件返回true,不存在返回false * @throws messagingexception * @throws ioexception */ public boolean iscontainattachment(part part) throws messagingexception, ioexception { boolean flag = false; if (part.ismimetype("multipart/*")) { mimemultipart multipart = (mimemultipart) part.getcontent(); int partcount = multipart.getcount(); for (int i = 0; i < partcount; i ) { bodypart bodypart = multipart.getbodypart(i); string disp = bodypart.getdisposition(); if (disp != null && (disp.equalsignorecase(part.attachment) || disp.equalsignorecase(part.inline))) { flag = true; } else if (bodypart.ismimetype("multipart/*")) { flag = iscontainattachment(bodypart); } else { string contenttype = bodypart.getcontenttype(); if (contenttype.indexof("application") != -1) { flag = true; } if (contenttype.indexof("name") != -1) { flag = true; } } if (flag) break; } } else if (part.ismimetype("message/rfc822")) { flag = iscontainattachment((part) part.getcontent()); } return flag; } /** * 判断邮件是否已读 * * @param msg 邮件内容 * @return 如果邮件已读返回true,否则返回false * @throws messagingexception */ public boolean isseen(mimemessage msg) throws messagingexception { return msg.getflags().contains(flags.flag.seen); } /** * 判断邮件是否需要阅读回执 * * @param msg 邮件内容 * @return 需要回执返回true,否则返回false * @throws messagingexception */ public boolean isreplysign(mimemessage msg) throws messagingexception { boolean replysign = false; string[] headers = msg.getheader("disposition-notification-to"); if (headers != null) replysign = true; return replysign; } /** * 获得邮件的优先级 * * @param msg 邮件内容 * @return 1(high):紧急 3:普通(normal) 5:低(low) * @throws messagingexception */ public string getpriority(mimemessage msg) throws messagingexception { string priority = "普通"; string[] headers = msg.getheader("x-priority"); if (headers != null) { string headerpriority = headers[0]; if (headerpriority.indexof("1") != -1 || headerpriority.indexof("high") != -1) priority = "紧急"; else if (headerpriority.indexof("5") != -1 || headerpriority.indexof("low") != -1) priority = "低"; else priority = "普通"; } return priority; } /** * 获得邮件文本内容 * * @param part 邮件体 * @param content 存储邮件文本内容的字符串 * @throws messagingexception * @throws ioexception */ public void getmailtextcontent(part part, stringbuffer content) throws messagingexception, ioexception { // 如果是文本类型的附件,通过getcontent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断 boolean iscontaintextattach = part.getcontenttype().indexof("name") > 0; if (part.ismimetype("text/*") && !iscontaintextattach) { content.append(part.getcontent().tostring()); } else if (part.ismimetype("message/rfc822")) { getmailtextcontent((part) part.getcontent(), content); } else if (part.ismimetype("multipart/*")) { multipart multipart = (multipart) part.getcontent(); int partcount = multipart.getcount(); for (int i = 0; i < partcount; i ) { bodypart bodypart = multipart.getbodypart(i); getmailtextcontent(bodypart, content); } } } /** * 保存附件 * * @param part 邮件中多个组合体中的其中一个组合体 * @param destdir 附件保存目录 * @throws unsupportedencodingexception * @throws messagingexception * @throws filenotfoundexception * @throws ioexception */ public void saveattachment(part part, string destdir) throws unsupportedencodingexception, messagingexception, filenotfoundexception, ioexception { if (part.ismimetype("multipart/*")) { multipart multipart = (multipart) part.getcontent(); // 复杂体邮件 // 复杂体邮件包含多个邮件体 int partcount = multipart.getcount(); for (int i = 0; i < partcount; i ) { // 获得复杂体邮件中其中一个邮件体 bodypart bodypart = multipart.getbodypart(i); // 某一个邮件体也有可能是由多个邮件体组成的复杂体 string disp = bodypart.getdisposition(); if (disp != null && (disp.equalsignorecase(part.attachment) || disp.equalsignorecase(part.inline))) { inputstream is = bodypart.getinputstream(); savefile(is, destdir, decodetext(bodypart.getfilename())); } else if (bodypart.ismimetype("multipart/*")) { saveattachment(bodypart, destdir); } else { string contenttype = bodypart.getcontenttype(); if (contenttype.indexof("name") != -1 || contenttype.indexof("application") != -1) { savefile(bodypart.getinputstream(), destdir, decodetext(bodypart.getfilename())); } } } } else if (part.ismimetype("message/rfc822")) { saveattachment((part) part.getcontent(), destdir); } } /** * 读取输入流中的数据保存至指定目录 * * @param is 输入流 * @param filename 文件名 * @param destdir 文件存储目录 * @throws filenotfoundexception * @throws ioexception */ private void savefile(inputstream is, string destdir, string filename) throws filenotfoundexception, ioexception { bufferedinputstream bis = new bufferedinputstream(is); bufferedoutputstream bos = new bufferedoutputstream(new fileoutputstream(new file(destdir filename))); int len = -1; while ((len = bis.read()) != -1) { bos.write(len); bos.flush(); } bos.close(); bis.close(); } public void setseen(mimemessage message) throws messagingexception {//设置文件已读 message.setflag(flags.flag.seen,true); } /** * 文本解码 * * @param encodetext 解码mimeutility.encodetext(string text)方法编码后的文本 * @return 解码后的文本 * @throws unsupportedencodingexception */ public string decodetext(string encodetext) throws unsupportedencodingexception { if (encodetext == null || "".equals(encodetext)) { return ""; } else { return mimeutility.decodetext(encodetext); } } }pop3协议接收邮件
import java.io.bufferedinputstream; import java.io.bufferedoutputstream; import java.io.file; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.unsupportedencodingexception; import java.text.simpledateformat; import java.util.date; import java.util.properties; import javax.mail.address; import javax.mail.bodypart; import javax.mail.flags; import javax.mail.folder; import javax.mail.message; import javax.mail.messagingexception; import javax.mail.multipart; import javax.mail.part; import javax.mail.session; import javax.mail.store; import javax.mail.internet.internetaddress; import javax.mail.internet.mimemessage; import javax.mail.internet.mimemultipart; import javax.mail.internet.mimeutility; import com.sun.mail.util.mailsslsocketfactory; /** * 使用pop3协议接收邮件 */ public class pop3receivemail { private string user = "";//账号 private string password = "";//密码 // private properties props = null; private folder folder = null;//收件箱 private store store = null;//实例对象 final string pop3 = "pop3"; // final string imap = "imap"; public pop3receivemail(string user,string password) { this.password = password;//密码 this.user = user;//账户 } /** * 接收邮件 */ public folder resceive() throws exception { /** * 因为现在使用的是163邮箱 而163的 pop地址是 pop3.163.com 端口是 110 比如使用好未来企业邮箱 就需要换成 好未来邮箱的 * pop服务器地址 pop.263.net 和 端口 110 */ string duankou = ""; // 端口号 string servicepath = ""; // 服务器地址 if(user==null||user.length()==0) throw new emailexception("账户不能为空!!!!"); if(password==null||password.length()==0) throw new emailexception("密码不能为空!!!!"); if(user.contains("@163")) { duankou = "110"; // 端口号 servicepath = "pop3.163.com"; // 服务器地址 }else if(user.contains("@qq")) { duankou = "995"; // 端口号 servicepath = "pop.qq.com"; // 服务器地址 }else { throw new emailexception("不支持该协议"); } // 准备连接服务器的会话信息 properties props = new properties(); props.setproperty("mail.store.protocol", pop3); // 使用pop3协议 // props.setproperty("mail.transport.protocol", pop3); // 使用pop3协议 props.setproperty("mail.pop3.port", duankou); // 端口 props.setproperty("mail.pop3.host", servicepath); // pop3服务器 props.setproperty("mail.pop3.socketfactory.fallback", "true"); mailsslsocketfactory sf = new mailsslsocketfactory();//ssl加密 sf.settrustallhosts(true); props.put("mail.pop3.ssl.enable", "true"); props.put("mail.pop3.ssl.socketfactory", sf); // final string ssl_factory = "javax.net.ssl.sslsocketfactory"; // security.addprovider(new com.sun.net.ssl.internal.ssl.provider()); // props.setproperty("mail.pop3.socketfactory.class", ssl_factory); // 创建session实例对象 session session = session.getinstance(props); store = session.getstore(pop3); store.connect(servicepath,user,password); // 163邮箱程序登录属于第三方登录所以这里的密码是163给的授权密码而并非普通的登录密码 // 获得收件箱 folder = store.getfolder("inbox"); /* * folder.read_only:只读权限 folder.read_write:可读可写(可以修改邮件的状态) */ // folder.open(folder.read_write); // 打开收件箱 folder.open(folder.read_write); // 打开收件箱 // 由于pop3协议无法获知邮件的状态,所以getunreadmessagecount得到的是收件箱的邮件总数 // system.out.println("未读邮件数: " folder.getunreadmessagecount()); // 由于pop3协议无法获知邮件的状态,所以下面得到的结果始终都是为0 // system.out.println("删除邮件数: " folder.getdeletedmessagecount()); // system.out.println("新邮件: " folder.getnewmessagecount()); // 获得收件箱中的邮件总数 // system.out.println("邮件总数: " folder.getmessagecount()); // 得到收件箱中的所有邮件,并解析 // message[] messages = folder.getmessages(); // parsemessage(messages); // 得到收件箱中的所有邮件并且删除邮件 // deletemessage(messages); // 释放资源 // folder.close(true); // store.close(); return folder; } public void colsefolder() throws messagingexception {//关闭资源 if(folder!=null) { folder.close(); } if(store!=null) { store.close(); } } /** * 解析邮件 * * @param messages 要解析的邮件列表 */ public void parsemessage(message... messages) throws messagingexception, ioexception { if (messages == null || messages.length < 1) throw new messagingexception("未找到要解析的邮件!"); // 解析所有邮件 for (int i = 0, count = messages.length; i < count; i ) { mimemessage msg = (mimemessage) messages[i]; system.out.println("------------------解析第" msg.getmessagenumber() "封邮件-------------------- "); system.out.println("主题: " getsubject(msg)); system.out.println("发件人: " getfrom(msg)); system.out.println("收件人:" getreceiveaddress(msg, null)); system.out.println("发送时间:" getsentdate(msg, null)); system.out.println("是否已读:" isseen(msg)); system.out.println("邮件优先级:" getpriority(msg)); system.out.println("是否需要回执:" isreplysign(msg)); system.out.println("邮件大小:" msg.getsize() * 1024 "kb"); boolean iscontainerattachment = iscontainattachment(msg); system.out.println("是否包含附件:" iscontainerattachment); if (iscontainerattachment) { saveattachment(msg, "f:\\mailtest\\" msg.getsubject() "_" i "_"); // 保存附件 } stringbuffer content = new stringbuffer(30); getmailtextcontent(msg, content); system.out.println("邮件正文:" (content.length() > 100 ? content.substring(0, 100) "..." : content)); system.out.println("------------------第" msg.getmessagenumber() "封邮件解析结束-------------------- "); system.out.println(); } } /** * 解析邮件 * * @param messages 要解析的邮件列表 */ public void deletemessage(message... messages) throws messagingexception, ioexception { if (messages == null || messages.length < 1) throw new messagingexception("未找到要解析的邮件!"); // 解析所有邮件 for (int i = 0, count = messages.length; i < count; i ) { /** * 邮件删除 */ message message = messages[i]; string subject = message.getsubject(); // set the delete flag to true message.setflag(flags.flag.deleted, true); system.out.println("marked delete for message: " subject); } } /** * 获得邮件主题 * * @param msg 邮件内容 * @return 解码后的邮件主题 */ public string getsubject(mimemessage msg) throws unsupportedencodingexception, messagingexception { return mimeutility.decodetext(msg.getsubject()); } /** * 获得邮件发件人 * * @param msg 邮件内容 * @return 姓名
* message.recipienttype.to 收件人 *
** message.recipienttype.cc 抄送 *
** message.recipienttype.bcc 密送 *
* * @param msg 邮件内容 * @param type 收件人类型 * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ... * @throws messagingexception */ public string getreceiveaddress(mimemessage msg, message.recipienttype type) throws messagingexception { stringbuffer receiveaddress = new stringbuffer(); address[] addresss = null; if (type == null) { addresss = msg.getallrecipients(); } else { addresss = msg.getrecipients(type); } if (addresss == null || addresss.length < 1) throw new messagingexception("没有收件人!"); for (address address : addresss) { internetaddress internetaddress = (internetaddress) adhttp://www.cppcns.comdress; receiveaddress.append(internetaddress.tounicodestring()).append(","); } receiveaddress.deletecharat(receiveaddress.length() - 1); // 删除最后一个逗号 return receiveaddress.tostring(); } /** * 获得邮件发送时间 * * @param msg 邮件内容 * @return yyyy年mm月dd日 星期x hh:mm * @throws messagingexception */ public string getsentdate(mimemessage msg, string pattern) throws messagingexception { date receiveddate = msg.getsentdate(); if (receiveddate == null) return ""; if (pattern == null || "".equals(pattern)) pattern = "yyyy年mm月dd日 e hh:mm "; return new simpledateformat(pattern).format(receiveddate); } /** * 判断邮件中是否包含附件 * * @param msg 邮件内容 * @return 邮件中存在附件返回true,不存在返回false * @throws messagingexception * @throws ioexception */ public boolean iscontainattachment(part part) throws messagingexception, ioexception { boolean flag = false; if (part.ismimetype("multipart/*")) { mimemultipart multipart = (mimemultipart) part.getcontent(); int partcount = multipart.getcount(); for (int i = 0; i < partcount; i ) { bodypart bodypart = multipart.getbodypart(i); string disp = bodypart.getdisposition(); if (disp != null && (disp.equalsignorecase(part.attachment) || disp.equalsignorecase(part.inline))) { flag = true; } else if (bodypart.ismimetype("multipart/*")) { flag = iscontainattachment(bodypart); } else { string contenttype = bodypart.getcontenttype(); if (contenttype.indexof("application") != -1) { flag = true; } if (contenttype.indexof("name") != -1) { flag = true; } } if (flag) break; } } else if (part.ismimetype("message/rfc822")) { flag = iscontainattachment((part) part.getcontent()); } return flag; } /** * 判断邮件是否已读 * * @param msg 邮件内容 * @return 如果邮件已读返回true,否则返回false * @throws messagingexception */ public boolean isseen(mimemessage msg) throws messagingexception { return msg.getflags().contains(flags.flag.seen); } /** * 判断邮件是否需要阅读回执 * * @param msg 邮件内容 * @return 需要回执返回true,否则返回false * @throws messagingexception */ public boolean isreplysign(mimemessage msg) throws messagingexception { boolean replysign = false; string[] headers = msg.getheader("disposition-notification-to"); if (headers != null) replysign = true; return replysign; } /** * 获得邮件的优先级 * * @param msg 邮件内容 * @return 1(high):紧急 3:普通(normal) 5:低(low) * @throws messagingexception */ public string getpriority(mimemessage msg) throws messagingexception { string priority = "普通"; string[] headers = msg.getheader("x-priority"); if (headers != null) { string headerpriority = headers[0]; if (headerpriority.indexof("1") != -1 || headerpriority.indexof("high") != -1) priority = "紧急"; else if (headerpriority.indexof("5") != -1 || headerpriority.indexof("low") != -1) priority = "低"; else priority = "普通"; } return priority; } /** * 获得邮件文本内容 * * @param part 邮件体 * @param content 存储邮件文本内容的字符串 * @throws messagingexception * @throws ioexception */ public void getmailtextcontent(part part, stringbuffer content) throws messagingexception, ioexception { // 如果是文本类型的附件,通过getcontent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断 boolean iscontaintextattach = part.getcontenttype().indexof("name") > 0; if (part.ismimetype("text/*") && !iscontaintextattach) { content.append(part.getcontent().tostring()); } else if (part.ismimetype("message/rfc822")) { getmailtextcontent((part) part.getcontent(), content); } else if (part.ismimetype("multipart/*")) { multipart multipart = (multipart) part.getcontent(); int partcount = multipart.getcount(); for (int i = 0; i < partcount; i ) { bodypart bodypart = multipart.getbodypart(i); getmailtextcontent(bodypart, content); } } } /** * 保存附件 * * @param part 邮件中多个组合体中的其中一个组合体 * @param destdir 附件保存目录 * @throws unsupportedencodingexception * @throws messagingexception * @throws filenotfoundexception * @throws ioexception */ public void saveattachment(part part, string destdir) throws unsupportedencodingexception, messagingexception, filenotfoundexception, ioexception { if (part.ismimetype("multipart/*")) { multipart multipart = (multipart) part.getcontent(); // 复杂体邮件 // 复杂体邮件包含多个邮件体 int partcount = multipart.getcount(); for (int i = 0; i < partcount; i ) { // 获得复杂体邮件中其中一个邮件体 bodypart bodypart = multipart.getbodypart(i); // 某一个邮件体也有可能是由多个邮件体组成的复杂体 string disp = bodypart.getdisposition(); if (disp != null && (disp.equalsignorecase(part.attachment) || disp.equalsignorecase(part.inline))) { inputstream is = bodypart.getinputstream(); savefile(is, destdir, decodetext(bodypart.getfilename())); } else if (bodypart.ismimetype("multipart/*")) { saveattachment(bodypart, destdir); } else { string contenttype = bodypart.getcontenttype(); if (contenttype.indexof("name") != -1 || contenttype.indexof("application") != -1) { savefile(bodypart.getinputstream(), destdir, decodetext(bodypart.getfilename())); } } } } else if (part.ismimetype("message/rfc822")) { saveattachment((part) part.getcontent(), destdir); } } /** * 读取输入流中的数据保存至指定目录 * * @param is 输入流 * @param filename 文件名 * @param destdir 文件存储目录 * @throws filenotfoundexception * @throws ioexception */ private void savefile(inputstream is, string destdir, string filename) throws filenotfoundexception, ioexception { bufferedinputstream bis = new bufferedinputstream(is); bufferedoutputstream bos = new bufferedoutputstream(new fileoutputstream(new file(destdir filename))); int len = -1; while ((len = bis.read()) != -1) { bos.write(len); bos.flush(); } bos.close(); bis.close(); } /** * 文本解码 * * @param encodetext 解码mimeutility.encodetext(string text)方法编码后的文本 * @return 解码后的文本 * @throws unsupportedencodingexception */ public string decodetext(string encodetext) throws unsupportedencodingexception { if (encodetext == null || "".equals(encodetext)) { return ""; } else { return mimeutility.decodetext(encodetext); } } }发送邮件
import java.io.file; import java.io.ioexception; import java.io.unsupportedencodingexception; import java.security.generalsecurityexception; import java.util.date; import java.util.properties; import java.util.uuid; import java.util.regex.matcher; import java.util.regex.pattern; import javax.activation.datahandler; import javax.activation.filedatasource; import javax.mail.bodypart; import javax.mail.message; import javax.mail.messagingexception; import javax.mail.multipart; import javax.mail.session; import javax.mail.transport; import javax.mail.internet.addressexception; 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; import com.sun.mail.util.mailsslsocketfactory; /* * 发送邮件 */ public class sendmailutil { private string host = ""; // smtp服务器 private string from = ""; // 发件人地址 // private string to = ""; // 收件人地址 private string[] affix = null; // 附件地址 // private string affixname = ""; // 附件名称 private string user = ""; // 用户名 private string pwd = ""; // 163的授权码 // private string subject = ""; // 邮件标题 private string[] tos = null; private properties props = null;// /** * @param user 账户名 * @param pwd 密码 * @param from 发件人地址 * @throws emailexception * @throws generalsecurityexception */ public sendmailutil(string user,string pwd,string from) throws emailexception, generalsecurityexception { this.user = user;//账户 this.pwd = pwd;//密码 this.from = from;//发件人地址 stratproperties(); } private void stratproperties() throws emailexception, generalsecurityexception { props = new properties(); if(user==null||user.length()==0) { throw new emailexception("邮箱账号不能为空"); }else { if(user.contains("@qq")) { host = "smtp.qq.com"; }else if(user.contains("@163")) { host = "smtp.163.com"; }else if(user.contains("@sina")) { host = "smtp.sina.com.cn"; }else { throw new emailexception("不支持该协议"); } // props.setproperty("mail.smtp.host", host);//设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器) // 设置邮件服务器主机名 props.setproperty("mail.host", host); } if(pwd==null||pwd.length()==0)throw new emailexception("邮箱密码不能为空"); props.setproperty("mail.transport.protocol", "smtp");// 发送邮件协议名称 props.setproperty("mail.smtp.auth", "true"); //需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条) // props.put("mail.debug", "true");//设置debug模式 后台输出邮件发送的过程 mailsslsocketfactory sf = new mailsslsocketfactory();//ssl加密 sf.settrustallhosts(true); props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.socketfactory", sf); } public void forwardmail(message message) throws addressexception, messagingexception, emailexception, ioexception { if(tos.length==0)throw new emailexception("收件人不能为空"); session session = session.getinstance(props);//用props对象构建一个session // session.setdebug(true);//关闭控制台输出 mimemessage newmessage = new mimemessage(session);//用session为参数定义消息对象 newmessage.setsubject(message.getsubject()); newmessage.setfrom(new internetaddress(from)); newmessage.setsentdate(new date()); newmessage.setcontent(message.getcontent(), message.getcontenttype()); internetaddress[] sendto = new internetaddress[tos.length]; // 加载收件人地址 for (int i = 0; i < tos.length; i ) { sendto[i] = new internetaddress(tos[i]); } newmessage.addrecipients(message.recipienttype.to,sendto); newmessage.addrecipients(mimemessage.recipienttype.cc, internetaddress.parse(from));//设置在发送给收信人之前给自己(发送方)抄送一份,不然会被当成垃圾邮件,报554错 transport smtp = session.gettransport("smtp"); smtp.connect(host, user, pwd); smtp.sendmessage(newmessage, newmessage.getallrecipients()); smtp.close(); } /** * @param path 需要添加附件的文件路径 * @throws emailexception */ public void addfile(string...path) throws emailexception { if(path==null||path.length==0)throw new emailexception("附件路径不能为空"); this.affix = path; } public void setto(string...to) throws emailexception { if(tostring().length()>0) { for(string t : to) { boolean emailformat = emailformat(t); if(!emailformat) { throw new emailexception(t "邮箱格式不正确"); } } tos = to; }else { throw new emailexception("收件人不能为空"); } } /** ** 验证输入的邮箱格式是否符合 * @param email * @return 是否合法 */ private boolean emailformat(string email) { boolean tag = true; final string pattern1 = "^([a-z0-9a-z] [-|\\.]?) [a-z0-9a-z]@([a-z0-9a-z] (-[a-z0-9a-z] )?\\.) [a-za-z]{2,}$"; final pattern pattern = pattern.compile(pattern1); final matcher mat = pattern.matcher(email); if (!mat.find()) { tag = false; } return tag; } /** * @param subject 标题 * @param context 文本信息 * @throws emailexception * @throws messagingexception * @throws addressexception * @throws generalsecurityexception * @throws unsupportedencodingexception */ public void send(string subject,string context) throws emailexception, addressexception, messagingexception, generalsecurityexception, unsupportedencodingexception { if(subject==null||subject.length()==0)subject=uuid.randomuuid().tostring(); // this.subject = subject;//标题 if(tos.length==0)throw new emailexception("收件人不能为空"); session session = session.getinstance(props);//用props对象构建一个session // session.setdebug(true);//关闭控制台输出 mimemessage message = new mimemessage(session);//用session为参数定义消息对象 message.setfrom(new internetaddress(from));// 加载发件人地址 internetaddress[] sendto = new internetaddress[tos.length]; // 加载收件人地址 for (int i = 0; i < tos.length; i ) { sendto[i] = new internetaddress(tos[i]); } message.addrecipients(message.recipienttype.to,sendto); message.addrecipients(mimemessage.recipienttype.cc, internetaddress.parse(from));//设置在发送给收信人之前给自己(发送方)抄送一份,不然会被当成垃圾邮件,报554错 message.setsubject(subject);//加载标题 multipart multipart = new mimemultipart();//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 bodypart contentpart = new mimebodypart();//设置邮件的文本内容 contentpart.settext(context); multipart.addbodypart(contentpart); if(affix!=null&&affix.length>0){//添加附件 for(int i = 0 ; i
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。