springMVC发送邮件
springMVC发送邮件
利用javax.mail发送邮件,图片与附件都可发送
1,Controller类
package com.web.controller.api; import javax.annotation.Resource; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import com.service.EmailService; @Controller
@RequestMapping("api")
public class EmailTaskController { private static final Logger logger = LoggerFactory.getLogger(EmailTaskController.class); @Resource
EmailService emailService; @RequestMapping("sendEmailTask")
public void sendEmailTask() {
logger.info("-------------执行发送邮件START---------------");
//写入excel
//insuranceService.excelManage();
//发邮件
emailService.emailManage(); logger.info("-------------执行发送邮件END---------------"); } }
2,service类
package com.service;
import com.entity.MailModel; public interface EmailService { /**
* email配置
* @return
*/
public boolean emailManage(); /**
* 发送邮件
* @param mail
*/
public boolean sendEmail(MailModel mail); }
package com.service.impl; import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage; import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service; import com.entity.MailModel;
import com.service.EmailService;
import com.SimpleException; @Service
public class EmailServiceImpl implements EmailService {
private static Logger logger = Logger.getLogger(EmailServiceImpl.class); private String excelPath = "d://"; @Resource
private JavaMailSender javaMailSender; @Resource
private SimpleMailMessage simpleMailMessage; @Override
public void emailManage(){
MailModel mail = new MailModel();
//主题
mail.setSubject("清单"); //附件
Map<String, String> attachments = new HashMap<String, String>();
attachments.put("清单.xlsx",excelPath+"清单.xlsx");
mail.setAttachments(attachments); //内容
StringBuilder builder = new StringBuilder();
builder.append("<html><body>你好!<br />");
builder.append("    附件是个人清单。<br />");
builder.append("    其中人信息;<br />");
builder.append("</body></html>");
String content = builder.toString(); mail.setContent(content); sendEmail(mail);
} /**
* 发送邮件
*
* @author chenyq
* @date 2016-5-9 上午11:18:21
* @throws Exception
*/
@Override
public void sendEmail(MailModel mail) {
// 建立邮件消息
MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper messageHelper;
try {
messageHelper = new MimeMessageHelper(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(";");
List<String> toEmailList = new ArrayList<String>();
if (null == toEmailArray || toEmailArray.length <= 0) {
throw new SimpleException("收件人邮箱不得为空!");
} else {
for (String s : toEmailArray) {
if (s!=null&&!s.equals("")) {
toEmailList.add(s);
}
}
if (null == toEmailList || toEmailList.size() <= 0) {
throw new SimpleException("收件人邮箱不得为空!");
} else {
toEmailArray = new String[toEmailList.size()];
for (int i = 0; i < toEmailList.size(); i++) {
toEmailArray[i] = toEmailList.get(i);
}
}
}
messageHelper.setTo(toEmailArray);
} else {
messageHelper.setTo(simpleMailMessage.getTo());
} // 邮件主题
if (mail.getSubject()!=null) {
messageHelper.setSubject(mail.getSubject());
} else { messageHelper.setSubject(simpleMailMessage.getSubject());
} // true 表示启动HTML格式的邮件
messageHelper.setText(mail.getContent(), true); // 添加图片
if (null != mail.getPictures()) {
for (Iterator<Map.Entry<String, String>> it = mail.getPictures().entrySet()
.iterator(); it.hasNext();) {
Map.Entry<String, String> entry = it.next();
String cid = entry.getKey();
String filePath = entry.getValue();
if (null == cid || null == filePath) {
throw new RuntimeException("请确认每张图片的ID和图片地址是否齐全!");
} File file = new File(filePath);
if (!file.exists()) {
throw new RuntimeException("图片" + filePath + "不存在!");
} FileSystemResource img = new FileSystemResource(file);
messageHelper.addInline(cid, img);
}
} // 添加附件
if (null != mail.getAttachments()) {
for (Iterator<Map.Entry<String, String>> it = mail.getAttachments()
.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, String> entry = it.next();
String cid = entry.getKey();
String filePath = entry.getValue();
if (null == cid || null == filePath) {
throw new RuntimeException("请确认每个附件的ID和地址是否齐全!");
} File file = new File(filePath);
if (!file.exists()) {
throw new RuntimeException("附件" + filePath + "不存在!");
} FileSystemResource fileResource = new FileSystemResource(file);
messageHelper.addAttachment(cid, fileResource);
}
}
messageHelper.setSentDate(new Date());
// 发送邮件
javaMailSender.send(message);
logger.info("------------发送邮件完成----------"); } catch (MessagingException e) { e.printStackTrace();
}
} }
MailModel实体类
package com.support.entity; import java.util.Map; public class MailModel { /**
* 发件人邮箱服务器
*/
private String emailHost;
/**
* 发件人邮箱
*/
private String emailFrom; /**
* 发件人用户名
*/
private String emailUserName; /**
* 发件人密码
*/
private String emailPassword; /**
* 收件人邮箱,多个邮箱以“;”分隔
*/
private String toEmails;
/**
* 邮件主题
*/
private String subject;
/**
* 邮件内容
*/
private String content;
/**
* 邮件中的图片,为空时无图片。map中的key为图片ID,value为图片地址
*/
private Map<String, String> pictures;
/**
* 邮件中的附件,为空时无附件。map中的key为附件ID,value为附件地址
*/
private Map<String, String> attachments; private String fromAddress;//发送人地址1个 private String toAddresses;//接收人地址,可以为很多个,每个地址之间用";"分隔,比方说450065208@qq.com;lpf@sina.com private String[] attachFileNames;//附件 public String getFromAddress() {
return fromAddress;
} public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
} public String getToAddresses() {
return toAddresses;
} public void setToAddresses(String toAddresses) {
this.toAddresses = toAddresses;
} public String getSubject() {
return subject;
} public void setSubject(String subject) {
this.subject = subject;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} public String[] getAttachFileNames() {
return attachFileNames;
} public void setAttachFileNames(String[] attachFileNames) {
this.attachFileNames = attachFileNames;
} public String getEmailHost() {
return emailHost;
} public void setEmailHost(String emailHost) {
this.emailHost = emailHost;
} public String getEmailFrom() {
return emailFrom;
} public void setEmailFrom(String emailFrom) {
this.emailFrom = emailFrom;
} public String getEmailUserName() {
return emailUserName;
} public void setEmailUserName(String emailUserName) {
this.emailUserName = emailUserName;
} public String getEmailPassword() {
return emailPassword;
} public void setEmailPassword(String emailPassword) {
this.emailPassword = emailPassword;
} public String getToEmails() {
return toEmails;
} public void setToEmails(String toEmails) {
this.toEmails = toEmails;
} public Map<String, String> getPictures() {
return pictures;
} public void setPictures(Map<String, String> pictures) {
this.pictures = pictures;
} public Map<String, String> getAttachments() {
return attachments;
} public void setAttachments(Map<String, String> attachments) {
this.attachments = attachments;
} }
spring.xml添加配置信息
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 发送邮件 -->
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>${mail.host}</value>
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
<property name="username">
<value>${mail.username}</value>
</property>
<property name="password">
<value>${mail.password}</value>
</property>
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean> <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="${mail.from}" />
<property name="subject" value="${mail.subject}" />
<property name="to" value="${mail.to}" />
<!--
<property name="text" value="邮件内容" />
-->
</bean>
</beans>
dev.properties配置
# email configuration
mail.host=smtp.163.com
mail.username=chenyanqing5945
mail.password=123456 mail.from=chenyanqing5945@163.com#发件人
mail.to=164792930@qq.com#收件人(多个用,隔开)
mail.subject=testEmail #主题
文件夹里有提供zip包
偶遇晨光原创
2016-05-20
springMVC发送邮件的更多相关文章
- 2016年工作中遇到的问题1-10:select-for-update锁表
1.select... for update锁表.注意事项:事务下使用,@Transactional如果用主键,只锁住1行记录如果不用主键,会锁住多条记录,mysql下测试,查询1条,锁住1行,查询2 ...
- springMVC下集成active MQ发送邮件
环境:本地需安装activemq,且访问正常,安装方法网上很多,这里省略. 1.添加相关jar包,我这里使用的是maven,你也可以选择其他方式添加.下面是maven相关配置: <!-- Act ...
- springmvc上传图片,发送邮件
package hcxAction; import hcxMode.Advertises; import hcxMode.Areas; import hcxMode.Saveresume; impor ...
- SpringMvc使用JavaMail发送邮件,并使用465端口开启ssl加密传输,保证邮件安全
代码在本地发邮件没任何问题.但部署到服务器,发送邮件显示连接异常.一开始非常懵逼,之后telnet smtp.163.com 25不通,发现是云服务器出于安全考虑,关闭了服务器的25端口,而25端口是 ...
- 【分享】标准springMVC+mybatis项目maven搭建最精简教程
文章由来:公司有个实习同学需要做毕业设计,不会搭建环境,我就代劳了,顺便分享给刚入门的小伙伴,我是自学的JAVA,所以我懂的.... (大图直接观看显示很模糊,请在图片上点击右键然后在新窗口打开看) ...
- springmvc 多数据源 SSM java redis shiro ehcache 头像裁剪
获取下载地址 QQ 313596790 A 调用摄像头拍照,自定义裁剪编辑头像 B 集成代码生成器 [正反双向](单表.主表.明细表.树形表,开发利器)+快速构建表单; 技术:31359679 ...
- java springMVC SSM 操作日志 4级别联动 文件管理 头像编辑 shiro redis
A 调用摄像头拍照,自定义裁剪编辑头像 B 集成代码生成器 [正反双向](单表.主表.明细表.树形表,开发利器)+快速构建表单; 技术:313596790freemaker模版技术 ,0个代码不用写 ...
- 解决springmvc+mybatis+mysql中文乱码问题【转】
这篇文章主要介绍了解决java中springmvc+mybatis+mysql中文乱码问题的相关资料,需要的朋友可以参考下 近日使用ajax请求springmvc后台查询mysql数据库,页面显示中文 ...
- Idea SpringMVC+Spring+MyBatis+Maven调整【转】
Idea SpringMVC+Spring+MyBatis+Maven整合 创建项目 File-New Project 选中左侧的Maven,选中右侧上方的Create from archetyp ...
随机推荐
- 初学JAVA 感想
开始学习任何一门课(包括java),兴趣最重要.一直觉得自己在学计算机编程语言,学习了很多,但每门语言都停留在知识边缘地带,都没深入到它们的精华部分,对它们的精华部分知之甚少,于是趁学校开设这门课,并 ...
- DOm4解析xml
1.创建XML文档对象的的方式有两种 1)Document document=DocumentHelper.createDocument(); 2)DocumentFactory documentFa ...
- ubuntu 14.04安装nginx+php+mysql
前段时间的折腾,颇费一番周折,过程中发现网上的许多资料比较老旧过时了,所以在这里也简单把过程重新整理一遍,争取一帖解决问题. 基于最新的Ubuntu 14.04(2014年9月)搭建nginx.php ...
- MySQL中函数CONCAT及GROUP_CONCAT
一.CONCAT()函数CONCAT()函数用于将多个字符串连接成一个字符串.使用数据表Info作为示例,其中SELECT id,name FROM info LIMIT 1;的返回结果为+----+ ...
- @SuppressWarnings("deprecation")
在Java编译过程中会出现很多警告,有很多是安全的,但是每次编译有很多警告影响我们对error的过滤和修改,我们可以在代码中加上 @SuppressWarnings("XXXX") ...
- Ajax在html页面获取后台XML文件资源
一.准备工具 站长吧ASP调试工具.exe,这个工具是为了快速建立asp环境,方便调试. 二.建立文件夹 1.建立网站根文件夹,名字随意,将站长吧ASP调试工具.exe复制到根文件夹: 2.建立xml ...
- 关于C语言的一些trick
很多东西已经记不起来了,想到一点写一点,碰到一点写一点,慢慢累积. 关于# #在宏定义中用于替换传入变量的字符,例如: #define whole_operation(n) do { printf( ...
- floyd算法
求两个顶点间的最短距离,直觉是这样的问题可以用尝试和枚举的办法来求解,这显然可行,但是我们可以换个方式来看待这个问题,比如, 可以这样描述,“在给定的点集(编号为1~k,k=图中所有的顶点数量)中,i ...
- CNC Fanuc 设备数据采集
为了这个Fanuc(发那科)数控机床数据的采集也花费了不少精力,先是去供应商那里了解,基本都是代理商,没有技术支持. 在网上也有关于Fanuc的以太网Ethernet连接文档,那里面有说明,大概是开发 ...
- [ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.3.1:
security-sdk-1.0.jar已经存在于D:/secServerSDK-test/src/main/resources/lib下 报错如下: xxxxxx@xxxxxxxx /d/secSe ...