java发送内嵌图片邮件
程序员文章站
2024-03-08 11:51:10
整体效果:
发送端:网易邮箱;接收端:qq邮箱。
1.web前端
2.在网易邮箱“已发送”中可以看见通过java代码发送的邮件
3.同样在qq邮箱中也可...
整体效果:
发送端:网易邮箱;接收端:qq邮箱。
1.web前端
2.在网易邮箱“已发送”中可以看见通过java代码发送的邮件
3.同样在qq邮箱中也可以看到这样的效果
实现过程:
1.web前端(bootstrap布局)
<form action="mailaction!sendmail" method="post" name="mailform" id="mailformid"> <ul class="list-group"> <li class="list-group-item"> <div class="input-group"> <span class="input-group-addon" id="basic-addon1">姓名:</span> <input type="text" class="form-control" placeholder="your name" name="mailform.name" aria-describedby="basic-addon1"> </div> </li> <li class="list-group-item"> <div class="input-group"> <span class="input-group-addon" id="basic-addon2">电话:</span> <input type="text" class="form-control" placeholder="your phone" name="mailform.phone" aria-describedby="basic-addon1"> </div> </li> <li class="list-group-item"> <div class="input-group"> <span class="input-group-addon" id="basic-addon2">邮件:</span> <input type="text" class="form-control" placeholder="your e-mail" name="mailform.e_mail" aria-describedby="basic-addon1"> </div> </li> <li class="list-group-item" style="padding-top: 20px;"> <span class="label label-default blog-label-1">消息:</span> <br><br> <textarea rows="10" style="width:100%" name="mailform.content" placeholder="请输入消息(不要超过500个字符)"></textarea> </li> <li class="list-group-item"> <center><button onclick="$('#mailformid').submit();" type="button" class="btn btn-success">发送邮件</button></center> </li> </ul> </form>
2.首先准备一个xml的模板(<xml-body>包含的是邮件的html格式的文本)。
<?xml version="1.0" encoding="utf-8"?> <!-- 将空格换成全角的空格,就可以保证html不会将空格过滤掉 --> <xml-body> <html> <head> </head> <body style="margin: 0; padding: 0;"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody><tr> <td style="padding: 10px 0 30px 0;"> <table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border: 1px solid #cccccc; border-collapse: collapse;"> <tbody><tr> <td align="center" bgcolor="#70bbd9" style="padding: 40px 0 30px 0; color: #153643; font-size: 28px; font-weight: bold; font-family: arial, sans-serif;"> <img src="cid:{4}" alt="creating email magic" width="300" height="230" style="display: block;"/> </td> </tr> <tr> <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody><tr> <td style="color: #153643; font-family: arial, sans-serif; font-size: 24px;"> <b> 发件人: {0} <br/> 电话: {1} <br/> 邮箱: {2} <br/> 内容:<br/> </b> </td> </tr> <tr> <td style="padding: 20px 0 30px 0; color: #153643; font-family: arial, sans-serif; font-size: 16px; line-height: 20px;"> {3} </td> </tr> <tr> <td> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody><tr> <td width="260" valign="top"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody><tr> <td> <img src="cid:{5}" alt="" width="100%" height="140" style="display: block;"/> </td> </tr> </tbody></table> </td> <td style="font-size: 0; line-height: 0;" width="20"> </td> <td width="260" valign="top"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody><tr> <td> <img src="cid:{6}" alt="" width="100%" height="140" style="display: block;"/> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </td> </tr> <tr> <td bgcolor="#ee4c50" style="padding: 30px 30px 30px 30px;"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody><tr> <td align="right" width="25%"> <table border="0" cellpadding="0" cellspacing="0"> <tbody><tr> <td style="font-family: arial, sans-serif; font-size: 12px; font-weight: bold;"> <img src="cid:{7}" alt="twitter" width="38" height="38" style="display: block;" border="0"/> </td> <td style="font-family: arial, sans-serif; font-size: 12px; font-weight: bold;"> <img src="cid:{8}" alt="facebook" width="38" height="38" style="display: block;" border="0"/> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </body> </html> </xml-body>
其中模板中会有一些标识符,如{i},表还是字符串的预留位置,然后通过messageformat格式化这样的消息,然后将格式化后的字符串插入到模式中的适当位置。
//得到xml的模板 string xml_path = servletactioncontext.getservletcontext().getrealpath("/mailtemplate")+"/mymailtemplete.xml"; string str=new readerxml().read(xml_path); object[] obj=new object[]{mailform.getname(), mailform.getphone(), mailform.gete_mail(), mailform.getcontent(), "e_mail", "left", "right", "tw", "fb"}; //messageformat可以格式化这样的消息,然后将格式化后的字符串插入到模式中的适当位置 string tcontent = messageformat.format(str, obj);
最终xml模板中的{i}分别被obj[i]替换了。
3.写一个对xml模板的类readerxml
public class readerxml { public string read(string path){ string str=null; str=reader(path); return str; } private string reader(string path){ saxreader reader=new saxreader(); string str=null; try { document d=reader.read(new file(path)); element e=d.getrootelement(); element htmle=e.element("html"); str=htmle.asxml(); } catch (documentexception e) { e.printstacktrace(); } return str; } }
4.最后就是我们的控制器类mailaction
在 html 格式的正文中内含图片是使用mimebodypart类的setcontentid() 方法设置对应的资源文件的唯一标识符,即 mime 协议对于邮件的结构组织格式中的 content-id 头字段,对应着xml模板中的cid:{i}标识, 如<img src="cid:{8}"/>(注:{i}会通过messageformat.format替换成对应的字符串)
public class mailaction extends actionsupport{ private mailform mailform; public mailform getmailform() { return mailform; } public void setmailform(mailform mailform) { this.mailform = mailform; } //添加内嵌图片 private mimebodypart createimagemimebodypart(string imagename) throws messagingexception, unsupportedencodingexception{ filedatasource fds=new filedatasource(servletactioncontext.getservletcontext().getrealpath("/image")+"/" + imagename + ".gif"); mimebodypart mbp=new mimebodypart(); datahandler dh=new datahandler(fds); mbp.setdatahandler(dh); //设置对应的资源文件的唯一标识符,即 mime 协议对于邮件的结构组织格式中的 content-id 头字段; mbp.setheader("content-id", imagename); mbp.setfilename(mimeutility.encodetext(fds.getname())); return mbp; } public string sendmail(){ try { httpservletrequest request = servletactioncontext.getrequest(); string pwd = "************";//发件人邮箱密码 string mailfrom = "***********@163.com"; //网易的邮箱 string wangyifrom = mailfrom.substring(0, mailfrom.indexof('@'));//网易邮箱的用户名 string tu = "163.com"; //发件人邮箱的后缀域名 string tto= "**********@qq.com"; //接收邮件的邮箱 string ttitle= "有人联系你---来自胡峻峥的个人网站"; //根据其物理路径,得到xml的模板 string xml_path = servletactioncontext.getservletcontext().getrealpath("/mailtemplate")+"/mymailtemplete.xml"; string str=new readerxml().read(xml_path); object[] obj=new object[]{mailform.getname(), mailform.getphone(), mailform.gete_mail(), mailform.getcontent(), "e_mail", "left", "right", "tw", "fb"}; //messageformat可以格式化这样的消息,然后将格式化后的字符串插入到模式中的适当位置 string tcontent = messageformat.format(str, obj); properties props=new properties(); props.put("mail.smtp.host","smtp."+tu);//邮箱smtp服务器地址端口 props.put("mail.smtp.auth","true");//这样才能通过验证 session s=session.getinstance(props); s.setdebug(true); mimemessage message=new mimemessage(s); //给消息对象设置发件人/收件人/主题/发信时间 internetaddress from; from = new internetaddress(mailfrom);//发件人的qq邮箱 message.setfrom(from); internetaddress to=new internetaddress(tto);//收件人的邮箱 message.setrecipient(message.recipienttype.to,to); message.setsubject(ttitle); message.setsentdate(new date()); //给消息对象设置内容 bodypart mbp=new mimebodypart();//新建一个存放信件内容的bodypart对象 mbp.setcontent(tcontent,"text/html;charset=gb2312");//给bodypart对象设置内容和格式/编码方式 // 用于组合文本和图片,"related"型的mimemultipart对象 multipart mm=new mimemultipart("related");//新建一个mimemultipart对象用来存放bodypart对象(事实上可以存放多个) mm.addbodypart(mbp);//将bodypart加入到mimemultipart对象中(可以加入多个bodypart) //添加图片 mm.addbodypart(createimagemimebodypart("e_mail")); mm.addbodypart(createimagemimebodypart("left")); mm.addbodypart(createimagemimebodypart("right")); mm.addbodypart(createimagemimebodypart("tw")); mm.addbodypart(createimagemimebodypart("fb")); message.setcontent(mm);//把mm作为消息对象的内容 message.savechanges(); transport transport=s.gettransport("smtp"); transport.connect("smtp."+tu, wangyifrom, pwd); //这里的wangyifrom为发件人网易账号 transport.sendmessage(message,message.getallrecipients()); transport.close(); actioncontext.getcontext().getsession().put("operations", "邮件发送成功, 请耐心等待回复!"); } catch (exception e) { system.out.println(e.tostring()); actioncontext.getcontext().getsession().put("errors", e.tostring()); return "errors"; } return "sendmail"; } }
以上就是本文的全部内容,希望对大家的学习有所帮助。
上一篇: java Socket UDP实例详解
下一篇: PHP的自定义模板引擎