springMVC发送邮件的简单实现
利用javax.mail发送邮件,图片与附件都可发送
1,Controller类
packagecom.web.controller.api; importjavax.annotation.Resource; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.stereotype.Controller; importorg.springframework.web.bind.annotation.RequestMapping; importcom.service.EmailService; @Controller @RequestMapping("api") publicclassEmailTaskController{ privatestaticfinalLoggerlogger=LoggerFactory.getLogger(EmailTaskController.class); @Resource EmailServiceemailService; @RequestMapping("sendEmailTask") publicvoidsendEmailTask(){ logger.info("-------------执行发送邮件START---------------"); //写入excel //insuranceService.excelManage(); //发邮件 emailService.emailManage(); logger.info("-------------执行发送邮件END---------------"); } }
2,service类
packagecom.service.impl; importjava.io.File; importjava.util.ArrayList; importjava.util.Date; importjava.util.HashMap; importjava.util.Iterator; importjava.util.List; importjava.util.Map; importjavax.annotation.Resource; importjavax.mail.MessagingException; importjavax.mail.internet.MimeMessage; importorg.apache.log4j.Logger; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.core.io.FileSystemResource; importorg.springframework.mail.SimpleMailMessage; importorg.springframework.mail.javamail.JavaMailSender; importorg.springframework.mail.javamail.MimeMessageHelper; importorg.springframework.stereotype.Service; importcom.entity.MailModel; importcom.service.EmailService; importcom.SimpleException; @Service publicclassEmailServiceImplimplementsEmailService{ privatestaticLoggerlogger=Logger.getLogger(EmailServiceImpl.class); privateStringexcelPath="d://"; @Resource privateJavaMailSenderjavaMailSender; @Resource privateSimpleMailMessagesimpleMailMessage; @Override publicvoidemailManage(){ MailModelmail=newMailModel(); //主题 mail.setSubject("清单"); //附件 Mapattachments=newHashMap (); attachments.put("清单.xlsx",excelPath+"清单.xlsx"); mail.setAttachments(attachments); //内容 StringBuilderbuilder=newStringBuilder(); builder.append("你好!
"); builder.append("    附件是个人清单。
"); builder.append("    其中人信息;
"); builder.append(""); Stringcontent=builder.toString(); mail.setContent(content); sendEmail(mail); } /** *发送邮件 * *@authorchenyq *@date2016-5-9上午11:18:21 *@throwsException */ @Override publicvoidsendEmail(MailModelmail){ //建立邮件消息 MimeMessagemessage=javaMailSender.createMimeMessage(); MimeMessageHelpermessageHelper; try{ messageHelper=newMimeMessageHelper(message,true,"UTF-8"); //设置发件人邮箱 if(mail.getEmailFrom()!=null){ messageHelper.setFrom(mail.getEmailFrom()); }else{ messageHelper.setFrom(simpleMailMessage.getFrom()); } //设置收件人邮箱 if(mail.getToEmails()!=null){ String[]toEmailArray=mail.getToEmails().split(";"); ListtoEmailList=newArrayList (); if(null==toEmailArray||toEmailArray.length<=0){ thrownewSimpleException("收件人邮箱不得为空!"); }else{ for(Strings:toEmailArray){ if(s!=null&&!s.equals("")){ toEmailList.add(s); } } if(null==toEmailList||toEmailList.size()<=0){ thrownewSimpleException("收件人邮箱不得为空!"); }else{ toEmailArray=newString[toEmailList.size()]; for(inti=0;i >it=mail.getPictures().entrySet() .iterator();it.hasNext();){ Map.Entry entry=it.next(); Stringcid=entry.getKey(); StringfilePath=entry.getValue(); if(null==cid||null==filePath){ thrownewRuntimeException("请确认每张图片的ID和图片地址是否齐全!"); } Filefile=newFile(filePath); if(!file.exists()){ thrownewRuntimeException("图片"+filePath+"不存在!"); } FileSystemResourceimg=newFileSystemResource(file); messageHelper.addInline(cid,img); } } //添加附件 if(null!=mail.getAttachments()){ for(Iterator >it=mail.getAttachments() .entrySet().iterator();it.hasNext();){ Map.Entry entry=it.next(); Stringcid=entry.getKey(); StringfilePath=entry.getValue(); if(null==cid||null==filePath){ thrownewRuntimeException("请确认每个附件的ID和地址是否齐全!"); } Filefile=newFile(filePath); if(!file.exists()){ thrownewRuntimeException("附件"+filePath+"不存在!"); } FileSystemResourcefileResource=newFileSystemResource(file); messageHelper.addAttachment(cid,fileResource); } } messageHelper.setSentDate(newDate()); //发送邮件 javaMailSender.send(message); logger.info("------------发送邮件完成----------"); }catch(MessagingExceptione){ e.printStackTrace(); } } }
MailModel实体类
packagecom.support.entity; importjava.util.Map; publicclassMailModel{ /** *发件人邮箱服务器 */ privateStringemailHost; /** *发件人邮箱 */ privateStringemailFrom; /** *发件人用户名 */ privateStringemailUserName; /** *发件人密码 */ privateStringemailPassword; /** *收件人邮箱,多个邮箱以“;”分隔 */ privateStringtoEmails; /** *邮件主题 */ privateStringsubject; /** *邮件内容 */ privateStringcontent; /** *邮件中的图片,为空时无图片。map中的key为图片ID,value为图片地址 */ privateMappictures; /** *邮件中的附件,为空时无附件。map中的key为附件ID,value为附件地址 */ privateMap attachments; privateStringfromAddress;//发送人地址1个 privateStringtoAddresses;//接收人地址,可以为很多个,每个地址之间用";"分隔,比方说450065208@qq.com;lpf@sina.com privateString[]attachFileNames;//附件 publicStringgetFromAddress(){ returnfromAddress; } publicvoidsetFromAddress(StringfromAddress){ this.fromAddress=fromAddress; } publicStringgetToAddresses(){ returntoAddresses; } publicvoidsetToAddresses(StringtoAddresses){ this.toAddresses=toAddresses; } publicStringgetSubject(){ returnsubject; } publicvoidsetSubject(Stringsubject){ this.subject=subject; } publicStringgetContent(){ returncontent; } publicvoidsetContent(Stringcontent){ this.content=content; } publicString[]getAttachFileNames(){ returnattachFileNames; } publicvoidsetAttachFileNames(String[]attachFileNames){ this.attachFileNames=attachFileNames; } publicStringgetEmailHost(){ returnemailHost; } publicvoidsetEmailHost(StringemailHost){ this.emailHost=emailHost; } publicStringgetEmailFrom(){ returnemailFrom; } publicvoidsetEmailFrom(StringemailFrom){ this.emailFrom=emailFrom; } publicStringgetEmailUserName(){ returnemailUserName; } publicvoidsetEmailUserName(StringemailUserName){ this.emailUserName=emailUserName; } publicStringgetEmailPassword(){ returnemailPassword; } publicvoidsetEmailPassword(StringemailPassword){ this.emailPassword=emailPassword; } publicStringgetToEmails(){ returntoEmails; } publicvoidsetToEmails(StringtoEmails){ this.toEmails=toEmails; } publicMap getPictures(){ returnpictures; } publicvoidsetPictures(Map pictures){ this.pictures=pictures; } publicMap getAttachments(){ returnattachments; } publicvoidsetAttachments(Map attachments){ this.attachments=attachments; } }
spring.xml添加配置信息
${mail.host} true 25000 ${mail.username} ${mail.password} UTF-8
dev.properties配置
#emailconfiguration mail.host=smtp.163.com mail.username=chenyanqing5945 mail.password=123456 mail.from=chenyanqing5945@163.com#发件人 mail.to=164792930@qq.com#收件人(多个用,隔开) mail.subject=testEmail#主题
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。