spring javamail 来发送动态生成的3D图象
- 格式:doc
- 大小:330.50 KB
- 文档页数:16
SpringBoot整合JavaMail通过阿⾥云企业邮箱发送邮件的实现JavaMail是Java开发中邮件处理的开源类库,⽀持常⽤协议如:SMTP、POP3、IMAP⼀、SpringBoot整合1、需要在pom⽂件中添加依赖spring-boot-starter-mail<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>构建项⽬,加载相关jar包2、在application.yml中配置邮件发送的相关信息spring:mail:host: #阿⾥云发送服务器地址port: 25 #端⼝号username: XXX@ #发送⼈地址password: ENC(Grg2n2TYzgJv9zpwufsf37ndTe+M1cYk) #密码3、编写邮件发送⼯具类MailUtilMailUtil.java/*** @author chenzan* @version V1.0* @description 邮件发送*/@Componentpublic class MailUtil {@AutowiredJavaMailSendermailSender;@AutowiredMailPropertiesmailProperties;/*** 发送邮件测试⽅法*/public void sendMail(MailBean mailBean) {SimpleMailMessage mimeMessage =new SimpleMailMessage();mimeMessage.setFrom(mailProperties.getUsername());mimeMessage.setTo(mailBean.getToAccount());mimeMessage.setSubject(mailBean.getSubject());mimeMessage.setText(mailBean.getContent());mailSender.send(mimeMessage);}/*** 发送邮件-附件邮件* @param boMailBean*/public boolean sendMailAttachment(MailBean mailBean) {try {MimeMessage mimeMessage =mailSender.createMimeMessage();MimeMessageHelper helper =new MimeMessageHelper(mimeMessage, true);helper.setFrom(mailProperties.getUsername());helper.setTo(boMailBean.getToAccount());helper.setSubject(mailBean.getSubject());helper.setText(mailBean.getContent(), true);// 增加附件名称和附件helper.addAttachment(MimeUtility.encodeWord(boMailBean.getAttachmentFileName(), "utf-8", "B"), mailBean.getAttachmentFile());mailSender.send(mimeMessage);return true;}catch (MessagingException e) {e.printStackTrace();return false;}}MailBean.java/*** @author chenzan* @version V1.0*/@Datapublic class MailBean {private Stringsubject;private String content;private String toAccount;private File attachmentFile;private String attachmentFileName;}4.发送String email = "XXX@";String content="测试内容";String subject = "测试主题";MailBean mailBean =new MailBean ();mailBean .setToAccount(email);boMailBean.setSubject(subject );boMailBean.setContent(content);boolean resultSend =mailUtil.sendMailAttachment(boMailBean);⼆、查看阿⾥云邮箱设置⽀持SMTP/POP3/IMAP功能,轻松通过客户端软件(outlook、foxmail等)收发邮件。
java实现动态图⽚效果本⽂实例为⼤家分享了java实现动态图⽚效果,供⼤家参考,具体内容如下源码package forGame;import javax.imageio.ImageIO;import javax.swing.*;import java.awt.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;//动态效果public class Demo_1 extends JFrame{//背景private BufferedImage bufferedImage;//窗体⼤⼩private int width;private int height;//要绘制的动态照⽚数组private BufferedImage[] images = new BufferedImage[4];//要绘制动态图中的那张private BufferedImage image;//初始化{if(bufferedImage == null){try {bufferedImage = ImageIO.read(new File("src\\image\\背景.png"));for(int i = 1;i < images.length + 1;i ++)images[i - 1] = ImageIO.read(new File("src\\image\\⼤飞机爆炸" + i + ".png"));} catch (IOException e) {e.printStackTrace();}}width = bufferedImage.getWidth();height = bufferedImage.getHeight();image = images[0];}public Demo_1(){super("动态测试");//设置窗⼝setSize(width,height);setLocationRelativeTo(null);setResizable(false);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setVisible(true);//启动线程MyThread myThread = new MyThread();myThread.start();}//双缓冲绘制解决图⽚闪烁问题@Overridepublic void paint(Graphics g) {Image image = this.createImage(width,height);Graphics gImage = image.getGraphics();gImage.setColor(gImage.getColor());gImage.fillRect(0,0,width,height);super.paint(gImage);//绘制背景gImage.drawImage(bufferedImage,0 ,0 ,null );//绘制动态图⽚gImage.drawImage(this.image,0 ,100 ,null );//最后绘制缓冲后的图⽚g.drawImage(image,0 ,0 , null);}private int num = 0;//images数组内图⽚索引//线程内部类private class MyThread extends Thread{@Overridepublic void run() {while(true) {if(num <= 3) {image = images[num ++];}elsenum = 0;repaint();try {sleep(100);//每隔100毫秒重绘⼀次} catch (InterruptedException e) {e.printStackTrace();}}}}public static void main(String[] args) {new Demo_1();}}效果图以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
Spring发送邮件_javax.mail.AuthenticationFailedExc。
在Spring项⽬中需要加⼊监控功能,监控过程中发现异常时,需要邮件报警。
最初选择⽤javamail发送,代码量⽐较⼤(相对于spring发送),最终选择Spring 邮件发送~下⾯贴⼀下实现的代码以及注意事项;这⾥只是简单的发送,如果需要发送附件或者HTML格式的邮件的话,代码在⽂章末尾[java]01. package mail;02. import javax.mail.MessagingException;03.04. import org.springframework.context.ApplicationContext;05. import org.springframework.context.support.FileSystemXmlApplicationContext;06. import org.springframework.mail.SimpleMailMessage;07. import org.springframework.mail.javamail.JavaMailSender;08. /**09. * @author Owner10. * springMail发送邮件11. * SendMail.java12. */13. public class SendMail {14. public ApplicationContext ctx = null;15. public SendMail() {16. ctx = new FileSystemXmlApplicationContext("src/mail/applicationContext-mail.xml");17. }18. /**19. * 主测试⽅法20. *21. * @throws MessagingException22. */23. public static void main(String[] args) {24. new SendMail().sendMail();25. }26. /**27. * 发送简单邮件28. */29. public void sendMail() {30. JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");// 获取JavaMailSender31. SimpleMailMessage mail = new SimpleMailMessage();32. try {33. mail.setTo("aaaa@");// 接受者34. mail.setFrom("bbbb@");// 发送者35. mail.setSubject("s邮件主题");// 主题36. mail.setText("springMail 的简单发送测试");// 邮件内容37. sender.send(mail);38. System.out.println("发送完毕");39. } catch (Exception e) {40. e.printStackTrace();41. }42. }43.44. }注意事项:在读取xml配置⽂件时,⽤的是FileSystemXmlApplicationContext实现类,在书写路径的时候不能只写⽂件名,尽管java⽂件和xml⽂件是在同⼀⽬录下。
使用spring发送javaMail配置简单,功能强大,可以发送普通的文本邮件,也可以发送html邮件,和模板邮件,同时可以设置异步发送,减少主业务线程的等待时间,废话不说直接上类和配置文件。
首先上MailServicele类package com.geelou.service;import java.util.HashMap;import java.util.Map;import javax.mail.MessagingException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import mons.logging.Log;import mons.logging.LogFactory;import org.springframework.core.task.TaskExecutor;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import er;import com.geelou.util.ConfigUtil;import freemarker.template.Configuration;import freemarker.template.Template;/*** 邮件服务* @author liqiang**/public class MailService{protected final Log logger = LogFactory.getLog(getClass());private JavaMailSender javaMailSender;private Configuration freemarkerConfiguration;private TaskExecutor taskExecutor;private String encoding = "utf-8";private static String from= ConfigUtil.getValue("admin_mail");private static String fromName =ConfigUtil.getValue("admin_mail_name");private static InternetAddress fromAddress;private InternetAddress getAddress(){if(fromAddress == null){try{fromAddress = new InternetAddress(from, fromName);}catch(Exception e){}}return fromAddress;}* 发送用户注册邮件* @param user*/public void sendRegistMail(User user){Map<String, Object> parseMap = new HashMap<String, Object>();parseMap.put("user", user);setAsyncTemplateMail(user.getEmail(), "欢迎来到geelou专业个人网站", encoding, "registerok.html", parseMap);}/*** 发送文本邮件*/public void sendSimpleMail(String to,String subject,String text){SimpleMailMessage msg = new SimpleMailMessage();msg.setFrom(from);msg.setTo(to);msg.setSubject(subject);msg.setText(text);javaMailSender.send(msg);}* 异步发送模版邮件* @param to* @param subject* @param encoding* @param template* @param parse* @throws Exception*/public void setAsyncTemplateMail(final String to,final String subject,final String encoding,final String template,finalMap<String,Object> parse){taskExecutor.execute(new Runnable() {public void run(){try{setTemplateMail(to,subject,encoding,template,parse);}catch (Exception e) {logger.error("邮件发送失败,失败提示:"+e.getMessage());}}});}/*** 发送模版邮件* @param to* @param subject* @param encoding* @param template* @param parse* @throws Exception*/public void setTemplateMail(String to,String subject,String encoding,String template,Map<String,Object> parse) throws Exception{ Template templateS =freemarkerConfiguration.getTemplate(template, encoding);String htmlCnt =FreeMarkerTemplateUtils.processTemplateIntoString(templateS, parse);sendHTMLMail(to,subject,htmlCnt,encoding);}/*** 发送html格式邮件* @param to* @param subject* @param htmlCnt* @param encoding* @throws MessagingException*/public void sendHTMLMail(String to,String subject,StringBuffer htmlCnt,String encoding) throws MessagingException{sendHTMLMail(to,subject,htmlCnt.toString(),encoding);}/*** 发送html格式邮件* @param to* @param subject* @param htmlCnt* @param encoding* @throws MessagingException*/public void sendHTMLMail(String to,String subject,String htmlCnt,String encoding) throws MessagingException{MimeMessage mimeMessage =javaMailSender.createMimeMessage();MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,false,encoding);mimeMessageHelper.setFrom(getAddress());mimeMessageHelper.setTo(to);mimeMessageHelper.setBcc(getAddress());mimeMessageHelper.setSubject(subject);mimeMessageHelper.setText(htmlCnt,true);javaMailSender.send(mimeMessage);}public void setJavaMailSender(JavaMailSender javaMailSender){ this.javaMailSender = javaMailSender;}public void setFreemarkerConfiguration(Configuration freemarkerConfiguration) {this.freemarkerConfiguration = freemarkerConfiguration;}public void setTaskExecutor(TaskExecutor taskExecutor) {this.taskExecutor = taskExecutor;}}下面是 spring applicationContext.xml里面关于mail的配置<!-- email有关配置 --><!-- 配置异步发送器--><bean id="taskExecutor"class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecut or"><property name="corePoolSize" value="10"/><property name="maxPoolSize" value="30"/></bean><!-- 配置邮件模板相关信息 --><bean id="freemarkerConfiguration"class="org.springframework.ui.freemarker.FreeMarkerConfigurationFacto ryBean"><property name="templateLoaderPath"value="classpath:/com/mcp/service/mail" /></bean><!-- 配置spring的javamail --><bean id="javaMailSender"class="org.springframework.mail.javamail.JavaMailSenderImpl"><!-- smtp地址 --><property name="host" value=""></property><!-- 端口 --><property name="port" value="465"></property><!-- 邮件发送地址 --><property name="username" value="admin@"></property><!-- 发送密码 --><property name="password" value="aaaaaa"></property><!-- 发送时使用的字符集 --><property name="defaultEncoding" value="UTF-8"></property><!-- javaMail相关参数设置 --><property name="javaMailProperties"><props><!-- 发送模式 debug --><prop key="mail.debug">true</prop><!-- 指定ssl --><propkey="mail.smtp.socketFactory.class">.ssl.SSLSocketFactory</p rop><!-- 是否需要auth认证 --><prop key="mail.smtp.auth">true</prop></props></property></bean>。
Java实现发送邮件,图⽚,附件1、JavaMail 介绍JavaMail 是sun公司(现以被甲⾻⽂收购)为⽅便Java开发⼈员在应⽤程序中实现邮件发送和接收功能⽽提供的⼀套标准开发包,它⽀持⼀些常⽤的邮件协议,如前⾯所讲的SMTP,POP3,IMAP,还有MIME等。
我们在使⽤JavaMail API 编写邮件时,⽆须考虑邮件的底层实现细节,只要调⽤JavaMail 开发包中相应的API类就可以了。
JavaMail 下载地址:2、JavaMail APIJavaMail API 按照功能可以划分为如下三⼤类:①、创建和解析邮件的API②、发送邮件的API③、接收邮件的API以上三种类型的API在JavaMail 中由多个类组成,但是主要有四个核⼼类,我们在编写程序时,记住这四个核⼼类,就很容易编写出Java邮件处理程序。
Message 类:javax.mail.Message 类是创建和解析邮件的核⼼ API,这是⼀个抽象类,通常使⽤它的⼦类javax.mail.internet.MimeMessage 类。
它的实例对象表⽰⼀份电⼦邮件。
客户端程序发送邮件时,⾸先使⽤创建邮件的 JavaMail API 创建出封装了邮件数据的 Message 对象,然后把这个对象传递给邮件发送API(Transport 类)发送。
客户端程序接收邮件时,邮件接收API把接收到的邮件数据封装在Message 类的实例中,客户端程序在使⽤邮件解析API从这个对象中解析收到的邮件数据。
Transport 类:javax.mail.Transport 类是发送邮件的核⼼API 类,它的实例对象代表实现了某个邮件发送协议的邮件发送对象,例如 SMTP 协议,客户端程序创建好Message 对象后,只需要使⽤邮件发送API 得到 Transport 对象,然后把 Message 对象传递给 Transport 对象,并调⽤它的发送⽅法,就可以把邮件发送给指定的 SMTP 服务器。
java发送内嵌图⽚邮件整体效果: 发送端:⽹易邮箱;接收端: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="" 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格式的⽂本)。
上次给大家分享了怎样发送简单邮件,本次给大家继续分享附件的发送、内嵌html、模版文件的发送。
发送带附件的邮件:Multipart email允许添加附件和内嵌资源(inline resources);使用一个简单的JPEG图片作为附件,android.png放在工程的根目录,以相对路径的方式加载。
发送内嵌资源的邮件:内嵌资源可能是你在信件中希望使用的图像或样式表,但是又不想把它们作为附件。
内嵌资源源使用Content-ID(上例中是android.png)来插入到mime信件中去。
加入文本和资源的顺序是非常重要的。
首先,先加入文本,随后是资源。
如果顺序弄反了,它将无法正常运作哦!使用Velocity模板来创建邮件内容:在之前的代码示例中,所有邮件的内容都是显式定义的,并通过调用message.setText(..)来设置邮件内容。
而在企业级应用程序中, 基于如下的原因,可能不会以上述方式创建你的邮件内容:1.使用Java代码来创建基于HTML的邮件内容不仅容易犯错,同时也是一件麻烦的事情2.将无法将显示逻辑和业务逻辑很明确的区分开3.一旦需要修改邮件内容的显式格式和内容,你需要重新编写Java代码,重新编译,重新部署……一般来说解决这些问题的典型的方式是使用FreeMarker或者Velocity这样的模板语言来定义邮件内容的显式结构。
这样,只要创建在邮件模板中需要展示的数据,并发送邮件即可。
通过使用Spring对FreeMarker和Velocity的支持类,你的邮件内容将变得简单,这同时也是一个最佳实践。
下面是一个使用Velocity来创建邮件内容的例子:使用Velocity模板发送邮件的具体开发步骤:一、添加Velocity依赖的jar文件二、Classpath路径添加模版文件velocity.vm三.模型对象User四、WelcomeService业务对象五、Junit六、等着收邮箱吧你还在等什么,赶紧试试吧。
Java 发送使用Java应用程序发送E-mail十分简单,但是首先你应该在你的机器上安装JavaMail API 和Java Activation Framework (JAF) 。
•您可以从Java 下载最新版本的JavaMail,打开网页右侧有个Downloads,点击它下载。
•您可以从Java 下载最新版本的JAF(版本1.1.1)。
你也可以使用本站提供的下载:•JavaMail mail.jar 1.4.5••JAF(版本1.1.1)activation.jar•下载并解压缩这些文件,在新创建的顶层目录中,您会发现这两个应用程序的一些jar 文件。
您需要把mail.jar和activation.jar文件添加到您的CLASSPATH 中。
如果你使用第三方服务器如QQ的SMTP服务器,可查看文章底部用户认证完整的实例。
发送一封简单的E-mail下面是一个发送简单E-mail的例子。
假设你的localhost已经连接到网络。
// 收件人电子String to = "abcdgmail.";// 发件人电子String from = "webgmail.";// 指定发送的主机为localhostString host = "localhost";// 获取系统属性Properties properties = System.getProperties();// 设置服务器properties.setProperty("mail.smtp.host", host);// 获取默认session对象Session session = Session.getDefaultInstance(properties);try{// 创建默认的MimeMessage 对象MimeMessage message = new MimeMessage(session);// Set From: 头部头字段message.setFrom(new InternetAddress(from));// Set To: 头部头字段message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));// Set Subject: 头部头字段message.setSubject("This is the Subject Line!");// 设置消息体message.setText("This is actual message");// 发送消息Transport.send(message);System.out.println("Sent message successfully....");}catch (MessagingException mex) {mex.printStackTrace();}}}编译并运行这个程序来发送一封简单的E-mail:如果你想发送一封给多个收件人,那么使用下面的方法来指定多个收件人ID:下面是对于参数的描述:•type:要被设置为TO, CC 或者BCC. 这里CC 代表抄送、BCC 代表秘密抄送y. 举例:Message.RecipientType.TO•addresses:这是email ID的数组。
springboot集成spring-boot-starter-mail邮件功能Spring Boot是由Pivotal团队提供的全新框架,其设计⽬的是⽤来简化新Spring应⽤的初始搭建以及开发过程。
该框架使⽤了特定的⽅式来进⾏配置,从⽽使开发⼈员不再需要定义样板化的配置。
通过这种⽅式,Spring Boot致⼒于在蓬勃发展的快速应⽤开发领域(rapid application development)成为领导者。
总之就是springboot 真⾹相信使⽤过Spring的众多开发者都知道Spring提供了⾮常好⽤的JavaMailSender接⼝实现邮件发送。
在Spring Boot的Starter模块中也为此提供了⾃动化配置。
下⾯通过实例看看如何在Spring Boot中使⽤JavaMailSender发送邮件。
1.使⽤普通的maven项⽬需要加⼊spring-context-support依赖,因为JavaMailSenderImpl类在这个包下⾯:2.使⽤springboot 需要引⼊<!-- email --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>依赖引⼊之后在我们的配置⽂件中做如下配置注意这⾥⾯的密码是我们邮箱的授权码不是登陆的密码另外有上传到服务器中报错⽆法使⽤的⽐如阿⾥云腾讯云以腾讯云为例可以申请去解封25端⼝百度很多⽅法。
在这只提⼀下这个问题在本博客只演⽰的发送邮件和附件/*** ⽆附件简单⽂本内容发送* @param email 接收⽅email* @param subject 邮件内容主题* @param text 邮件内容*/public void simpleMailSend(String email,String subject,String text) {//创建邮件内容SimpleMailMessage message=new SimpleMailMessage();message.setFrom(username);//这⾥指的是发送者的账号message.setTo(email);message.setSubject(subject);message.setText(text);//发送邮件mailSender.send(message);System.out.println("\033[32;1m"+"发送给 "+email+" 的邮件发送成功"+"\033[0m");}/*** 发送带附件的邮件** @param to 接受⼈* @param subject 主题* @param html 发送内容* @param filePath 附件路径* @throws MessagingException 异常* @throws UnsupportedEncodingException 异常*/public void sendAttachmentMail(String to, String subject, String html, String filePath) throws MessagingException, UnsupportedEncodingException {MimeMessage mimeMessage = mailSender.createMimeMessage();// 设置utf-8或GBK编码,否则邮件会有乱码MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");messageHelper.setFrom(username,emailName);messageHelper.setTo(to);messageHelper.setSubject(subject);messageHelper.setText(html, true);FileSystemResource file=new FileSystemResource(new File(filePath));String fileName=filePath.substring(stIndexOf(File.separator));messageHelper.addAttachment(fileName,file);mailSender.send(mimeMessage);}/*** 发送html内容的邮件* @param email* @param subject* @param text*/public void sendSimpleMailHtml(String email,String subject,String text) throws MessagingException {MimeMessage mimeMessage = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);helper.setFrom(username);helper.setTo("demogogo@");helper.setSubject("主题:嵌⼊静态资源");// 注意<img/>标签,src='cid:jpg','cid'是contentId的缩写,'jpg'是⼀个标记helper.setText("<html><body><img src=\"cid:jpg\"></body></html>", true);// 加载⽂件资源,作为附件FileSystemResource file = new FileSystemResource(new File("C:\\Users\\吴超\\Pictures\\Camera Roll\\微信截图_20191016142536.png")); // 调⽤MimeMessageHelper的addInline⽅法替代成⽂件('jpg[标记]', file[⽂件])helper.addInline("jpg", file);// 发送邮件mailSender.send(mimeMessage);}打开我们的邮箱⼩姐姐到⼿。
利用Spring框架封装的JavaMail实现同步或异步邮件发送利用Spring框架封装的JavaMail现实同步或异步邮件发送作者:张纪豪J2EE简单地讲是在JDK上扩展了各类应用的标准规范,邮件处理便是其中一个重要的应用。
它既然是规范,那么我们就可以通过JDK遵照邮件协议编写一个邮件处理系统,但事实上已经有很多厂商和开源组织这样做了。
Apache 是J2EE最积极的实现者之一,当然还有我们的老大——SUN。
聊起老大,感慨万端!他已经加入Oracle——甲骨文(不是刻在乌龟壳上的那种文字吗?是我中华,也是人类上最早的语言啊,比Java早几千年哦),其掌门人拉里·埃里森是个不错的水手,别以为那只是在帆船上,至少他不至于盖茨那么不仁道——开源万岁。
有理由相信Java世界还有一段辉煌的历程。
Google 的Android和Chrome OS两大操作系统,还会首选Java作应用开发基础语言,即便是推出自己的易语言。
同时笔者预感到ChromeOS前景不可估量,它可能是推动云计算一个重要组成部分,Andtroid(主用在移动设备上,未来可能是手机上主流的操作系统),乃至微软的Windows将来可能都是该系统的小窗口而已。
微软已显得老态龙钟了,再与大势已去的雅虎合作,前进步伐必将大大减缓。
投资者此时可以长线买入Google股票(投资建议,必自判断)。
笔者也常用google搜索引擎、gmail。
好了,闲话少聊,言归主题。
可能大家如笔者一样用的最多的是老大的javamail,虽然老大实现了邮件功能,但调用起来还是需要较复杂的代码来完成,而且初学者调用成功率很低(因为它还要与外界服务器通信),这就使得初学者对于它越学越迷茫。
不过这方面的例子很多,因此笔者不再在此重复这些示例代码,而着重利用Spring 框架封装的邮件处理功能。
开工之前,我们先了解下环境。
笔者开的是web工程,所需要的基础配置如下:▲ JDK 1.6▲ J2EE 1.5▲ JavaMail 1.4 稍作说明:J2EE 1.5中已经纳入了邮件规范,因此在开发期不要导入javamail中的jar包,运行期则需要,因此可以将jar包放入到web容器的java库中(例如Tomcat的lib目录下),要了解其意可以参考数据库驱动包的运用。
spring javamail 来发送动态生成的3D图象在以前的工作项目中,也接触过javamail来发送简单的邮件,但是最近的一个项目在用javamail来发送html格式的邮件时,却遇到了点小麻烦。
因为客户要求要把在后台生成的3D报表图片(用JFreeChart 来实现)嵌入到html中。
其实发送html格式的邮件倒是没有什么困难,难就难在如何把在服务器端生成的3D图片也发送出去,并且不能把3D的图片存储在server上,因为是Web应用,访问量甚是惊人,如果每个用户都生成几个3D图片,不用很久服务器的存储空间就难以承受了。
还好经过我耐心地试验,问题终于得到了圆满解决,在此记录下来,以备不时之需,同时分享给像前几天的我一样被这个问题困扰的同行们。
首先配置spring的xml文件:<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" " /dtd/spring-beans.dtd"><beans><bean id="mailsender" class="org.springframework.mail.javamail.JavaMailSenderImpl" ><property name="host"><value></value></property><property name="username"><value>youruser</value></property><property name="password"><value>yourpassword</value></property><property name="javaMailProperties"><props><prop key="mail.smtp.auth">true</prop></props></property></bean><bean id="mailmessage" class="org.springframework.mail.SimpleMailMessage"> <property name="to"><value>youruser@</value></property><property name="from"><value>youruser@</value></property><property name="subject"><value>A sample mail</value></property></bean></beans>邮件工厂,采用工厂模式:/****/package com.kevin.springmail;import java.io.File;import java.io.IOException;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeUtility;import mons.logging.Log;import mons.logging.LogFactory;import org.apache.log4j.BasicConfigurator;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.core.io.FileSystemResource;import org.springframework.core.io.UrlResource;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSenderImpl;import org.springframework.mail.javamail.MimeMessageHelper;/*** @author Administrator* @date 2006-9-15* @time 22:16:34*/public class MailFactory {private static final Log logger = LogFactory.getLog(MailFactory.class);private static final ApplicationContext context;/*** 初始化beans*/static {//加载log4j日志记录BasicConfigurator.configure();String springbean = "com/kevin/springmail/springmail.xml";context = new ClassPathXmlApplicationContext(springbean);("初始化beans springmail.xml 完成!");}/*** 发送简单的邮件信息,邮件的内容都是纯文本的内容**/public static void sendSimpleMessageMail(){SimpleMailMessage mailmessage = (SimpleMailMessage)context.getBean("mailmes sage");JavaMailSenderImpl mailsender = (JavaMailSenderImpl)context.getBean("mailsend er");mailmessage.setText("你好,Jarry!");mailsender.send(mailmessage);("simple mail has bean sent !");}/*** 发送HTML格式的邮件,HTML格式中带有图片的,* 图片的来源是Server端的文件系统。
(图片就是文件系统的)* @throws MessagingException* @throws IOException*/public static void sendMimeMessageMail() throws MessagingException, IOException{JavaMailSenderImpl mailsender = (JavaMailSenderImpl)context.getBean("mailsend er");MimeMessage mimeMessage = mailsender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "GB23 12");StringBuffer html = new StringBuffer();html.append("<html>");html.append("<head>");html.append("<meta http-equiv='Content-Type' content='text/html; charset=gb23 12'>");html.append("</head>");html.append("<body bgcolor='#ccccff'>");html.append("<center>");html.append("<h1>你好,Jarry</h1>");html.append("<img src='cid:img'>");html.append("<p>logo:");html.append("<img src='cid:logo'>");html.append("</center>");html.append("</body>");html.append("</html>");helper.setText(html.toString(), true);FileSystemResource image = new FileSystemResource(new File("icon.gif"));helper.addInline("img",image);FileSystemResource logo = new FileSystemResource(new File("logo.gif"));helper.addInline("logo",logo);helper.setFrom("green006@");helper.setTo("green006@");helper.setSubject("spring javamail test");(mimeMessage.getContentID());(mimeMessage.getContent());mailsender.send(mimeMessage);("mime mail has bean sent !");}/*** 发送带动态图象的HTML邮件,所谓动态图象就是在发送邮件时* 动态地生成一个图片,然后再随HTML格式的邮件发送出去。