使用spring mail 实现的邮箱发送功能,包括附件的发送(附件发送要保证附件存在的路径是真实),使用maven集成jar包,通过spring mvc 实现前后台的调用,发送方使用的是163邮箱,发送邮箱需要授权码,要自己设置。此项目在配置文件中修改成自己的邮箱账号及授权码可以直接使用,真实项目中直接附件代码就可以使用

1、界面访问路径

http://localhost/mail/

2、界面样式

3、文件和接收人多个时,使用逗号分隔

4、实现方式,前台使用bootstrap、jquery、ajax;后台使用spring、spring mvc

5、工程整体结构

6、修改文件为自己的邮箱及授权码

7、本工程使用的是eclipse4.5 tomcat8.0 jdk1.8 如需下载请到公网下载

8、下载mail.rar 后将文件解压并将解压的文件导入到eclipse中

9、修改上图6中的配置文件

10、输入内容,成功发送后提示,发送成功

否则提示发送失败

11、如何申请一个163邮箱

点击注册邮箱,注册成功后需要修改授权码

点击设置先开通pop3

开通成功后点击客户端授权密码

点击重置,修改成自己设置的授权码(注授权码只显示一次,所以在设置时,一定要自己记住授权码)

12、代码实例

页面代码

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<title>邮件发送</title>
<!-- 引入公共文件 -->
<link rel="stylesheet" href="bootstrap-3.3.0-dist/dist/css/bootstrap.min.css">
<script type="text/javascript" src="jquery-2.1.4.js"></script>
<script type="text/javascript" src="bootstrap-3.3.0-dist/dist/js/bootstrap.min.js"></script>
<style type="text/css">
.form-horizontal .form-group {
    margin-right: 0px !important;
    margin-left: 0px !important;
}
</style>
<script>
$(function(){
$('#send').click(function(){
var people = $('#people').val();
var attachment = $('#attachment').val();
$.ajax({
  type: "POST",
  url: "http://localhost/mail/message/send/sendMail.action",
  data: {
  title:$('#title').val(),
  content:$('#content').val(),
  people:people.substring(0,people.length),
  attachment:attachment.substring(0,attachment.length),
  },
  success: function(data){

    if(data.status == 1){
     alert(data.msg);
    }else{
     alert(data.msg);
    }
  },
  error:function(){
alert("发送失败");
  }
});
});
})
</script>
</head>
<body>
<div>
    <form style="margin-top: 20px;">
  <div>
    <label for="inputEmail3" class="col-sm-2 control-label">标题</label>
    <div>
      <input type="text" id="title" placeholder="标题">
    </div>
  </div>
  <div>
    <label for="inputPassword3" class="col-sm-2 control-label">内容</label>
    <div>
      <textarea rows="3" id="content" placeholder="内容"></textarea>
    </div>
  </div>
  <div>
    <label for="inputPassword3" class="col-sm-2 control-label">附件</label>
    <div>
      <input type="text" id="attachment" placeholder="文件真实路径">
    </div>
  </div>
  <div>
    <label for="inputPassword3" class="col-sm-2 control-label">接收人</label>
    <div>
      <textarea rows="3" id="people" placeholder="123456789@qq.com"></textarea>
    </div>
  </div>
  <div>
    <div class="col-sm-offset-2 col-sm-10">
      <button type="button" id="send" class="btn btn-default">发送</button>
    </div>
  </div>
</form>
</div><!-- pageContainer -->
</body>
</html>

  后台代码controller

package com.messages.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.messages.ResponseData;
import com.messages.service.messageService;

/**
 * 登录控制器
 * @author xuchangcheng
 */
@Controller
@RequestMapping("/send")
public class messageController {

    @Autowired
    private messageService message;
    /**
     * 发送邮件
     * @param request
     * @return String
     */
    @RequestMapping(value="sendMail", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResponseData save(HttpServletRequest request,String title,String content,String people,String attachment){
        ResponseData responseData=new ResponseData();
        try{
            message.send(title,content, people,attachment);
            responseData.setStatus(1);
            responseData.setMsg("发送成功");
            responseData.setData(1);
            }  catch (Exception e) {
            e.printStackTrace();
            responseData.setStatus(2);
            responseData.setMsg("发送失败");
        }
        return  responseData;
    }

}

  service端

package com.messages.service;
import org.springframework.stereotype.Service;

@Service
public class messageService{

    /**
     * 发送邮件
     * @param
     * @return
     * @throws Exception
     */
    public void send(String title,String content,String people,String attachment) throws Exception{
        SpingMailSend sm = new SpingMailSend();
        String [] pe = people.split(",");
        if(attachment==""){
            sm.send(title, content,pe);
        }else{
            String [] at = attachment.split(",");
            sm.send(title, content,at, pe);
        }

    }
}

  短息发送的核心代码

package com.messages.service;

import java.io.File;
import java.io.UnsupportedEncodingException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.ApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.messages.WebContextListener;
public class SpingMailSend  {

    /************************************邮件核心***************************************/
    /**
     * 邮件发送 方法可设置发送,抄送,密送
     *
     * @param subject                邮件的标题
     * @param content                邮件正文
     * @param attachmenFiles[]       附件,需要真实位置
     * @param receiver               接收人
     * @param carbonCopyTo[]     抄送人邮箱地址(为数组)
     * @param blindCarbonCopyTo[]    密送人邮箱地址(为数组)
     * @return    boolean            邮件是否发成功
     * @throws MessagingException
     */
    public boolean send(String subject,String content,String[] receiver) throws Exception {
        boolean status = this.send(subject, content, null,receiver, null, null);
        return status;
    }
    public boolean send(String subject,String content,String[] attachmenFiles,String[] receiver) throws Exception {
        boolean status = this.send(subject, content, attachmenFiles,receiver, null, null);
        return status;
    }

    public boolean send(String subject,String content,String[] attachmenFiles,String[] receiver,String[] carbonCopyTo,String[] blindCarbonCopyTo) throws Exception {
        try {

            /*ServletContext sc = request.getSession().getServletContext();
            ApplicationContext ac2 = WebApplicationContextUtils  .getWebApplicationContext(sc);
            JavaMailSender mailSender = (JavaMailSender) ac2.getBean("mailSender");
            SimpleMailMessage mailMessage = (SimpleMailMessage) ac2.getBean("mailMessage");*/
            JavaMailSender mailSender = (JavaMailSender) WebContextListener.getBean("mailSender");
            SimpleMailMessage mailMessage = (SimpleMailMessage) WebContextListener.getBean("mailMessage");
            String from=mailMessage.getFrom();

            MimeMessage mime = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mime, true, "utf-8");
            helper.setSubject(subject);// 邮件主题
            helper.setText(content, true);// true表示设定html格式

            for(int i=0;attachmenFiles!=null&&i<attachmenFiles.length;i++){
                File file=new File(attachmenFiles[i]);
                helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
            }

            helper.setFrom(from);// 发件人
            helper.setTo(receiver);// 收件人
            if(carbonCopyTo!=null)
                helper.setCc(carbonCopyTo);

            if(blindCarbonCopyTo!=null)
                helper.setBcc(blindCarbonCopyTo);

            mailSender.send(mime);
            return true;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /*  非web端测试发送(java)
       public boolean send(String subject,String content,String[] attachmenFiles,String[] receiver,String[] carbonCopyTo,String[] blindCarbonCopyTo) throws Exception {
        try {
            ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-bean/spring-context-mail.xml");
            JavaMailSender mailSender = (JavaMailSender) ac.getBean("mailSender");
            SimpleMailMessage mailMessage = (SimpleMailMessage) ac.getBean("mailMessage");
            String from=mailMessage.getFrom();

            MimeMessage mime = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mime, true, "utf-8");
            helper.setSubject(subject);// 邮件主题
            helper.setText(content, true);// true表示设定html格式

            for(int i=0;attachmenFiles!=null&&i<attachmenFiles.length;i++){
                File file=new File(attachmenFiles[i]);
                helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
            }

            helper.setFrom(from);// 发件人
            helper.setTo(receiver);// 收件人
            if(carbonCopyTo!=null)
                helper.setCc(carbonCopyTo);

            if(blindCarbonCopyTo!=null)
                helper.setBcc(blindCarbonCopyTo);

            mailSender.send(mime);
            return true;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }*/

    /*public static void main(String[] args) throws Exception {

        SpingMailSend s=new SpingMailSend();
        String [] pe = new String[]{"123456789@qq.com"};
        s.send("163测试", "163测试邮箱发送", pe);
    }*/
}

  demo下载:http://www.wisdomdd.cn/Wisdom/resource/articleDetail.htm?resourceId=703

spring 实现邮箱发送的更多相关文章

  1. Spring Boot 整合Spring Data以及rabbitmq,thymeleaf,向qq邮箱发送信息

    首先得将自己的qq开启qq邮箱的POP3/SMTP服务 说明: p,e为路由key. 用户系统完成登录的时候,将{手机号-时间-IP}保存到队列Phone-queue中,msg-sys系统获得消息打印 ...

  2. JAVA 实现 QQ 邮箱发送验证码功能(不局限于框架)

    JAVA 实现 QQ 邮箱发送验证码功能(不局限于框架) 本来想实现 QQ 登录,有域名一直没用过,还得备案,好麻烦,只能过几天再更新啦. 先把实现的发送邮箱验证码更能更新了. 老规矩,更多内容在注释 ...

  3. SpringBoot中快速实现邮箱发送

    前言 在许多企业级项目中,需要用到邮件发送的功能,如: 注册用户时需要邮箱发送验证 用户生日时发送邮件通知祝贺 发送邮件给用户等 创建工程导入依赖 <!-- 邮箱发送依赖 --> < ...

  4. Spring Boot邮箱链接注册验证

    Spring Boot邮箱链接注册验证 简单介绍 注册流程 [1]前端提交注册信息 [2]后端接受数据 [3]后端生成一个UUID做为token,将token作为redis的key值,用户数据作为re ...

  5. Linux配置邮箱发送(MUTT/MSMTPQ)

    配置邮箱发送 http://www.ilanni.com/?p=10589

  6. java邮件发送 qq与163邮箱互发和qq和163邮箱发送其他邮箱实例

    研究了近一天的时间,通过查阅相关资料,终于对java发送邮件的机制,原理有了一点点的理解,希望能够帮到大家! 1.首先要向你的项目里导入1个jar包:mail-1.4.4.jar即可(实现qq和163 ...

  7. 通过邮箱发送html报表

    前言 需求是发送邮件时, 可以将报表正文贴到邮件里, 可以正常复制选中报表内容. 目前的做法是简单粗暴的转成了一张图片, 这样效果显然是很糟糕的. 今天看到邮箱里可以预览Word, Excel, F1 ...

  8. java邮箱发送

    一.为何要使用邮箱发送 相信大家在日常工作生活中少不了和邮件打交道,比如我们会用邮件进行信息交流,向上级汇报日常工作:邮件发送的原理是什么?邮件是如何发送的呢?本系列教程将会讲解邮件如何申请可用jav ...

  9. qq邮箱发送,mail from address must be same as authorization user

    由于邮箱发送的邮箱账号更换,所以重新测试.结果一直出错,要不就是请求超时,要不就是未授权. 用smtp 开始的时候,端口使用495,结果是请求超时. 后来改成25,结果是未授权. 再后来听人说,有一个 ...

随机推荐

  1. Visual Studio中将打开的代码与类文件进行关联

  2. InfluxDb中写入重复数据问题解决方案

    1.InfluxDb版本 0.10.3 2.Measurement TodayChargeTimeReport 只有time和Field列,没有Tag列 3.现象:通过定时任务向上面的表中写入数据: ...

  3. Asp.Net Web API(二)

    创建一个Web API项目 第一步,创建以下项目 当然,你也可以创建一个Web API项目,利用 Web API模板,Web API模板使用 ASP.Net MVC提供API的帮助页. 添加Model ...

  4. jspsmart(保存文件)+poi(读取excel文件)操作excel文件

    写在前面: 项目环境:jdk1.4+weblogic 需求:能上传excel2003+2007 由于项目不仅需要上传excel2003,还要上传excel2007,故我们抛弃了jxl(只能上传exce ...

  5. 前端构建之gulp与常用插件(转载)

    原博主:幻天芒 原文地址:http://www.cnblogs.com/humin/p/4337442.html gulp是什么? http://gulpjs.com/ 相信你会明白的! 与著名的构建 ...

  6. iOS知识点、面试题 之三

    最近面试,发现这些题 还不错,与大家分享一下,分三文给大家: 当然Xcode新版本区别,以及iOS新特性 Xcode8 和iOS 10 在之前文章有发过,感兴趣的可以查阅: http://www.cn ...

  7. go defer (go延迟函数)

    go defer (go延迟函数) Go语言的defer算是一个语言的新特性,至少对比当今主流编程语言如此.根据GO LANGUAGE SPEC的说法: A "defer" sta ...

  8. 关于ubuntu下qt编译显示Cannot connect creator comm socket /tmp/qt_temp.xxx/stub-socket的解决办法

    今天在ubuntu下安装了qtcreator,准备测试一下是否能用,果然一测试就出问题了,简单编写后F5编译在gnome-terminal中出现 Cannot connect creator comm ...

  9. Qt--自定义Delegate

    这是Model/View中的最后一篇了,Qt官方显然弱化了Controller在MVC中的作用,提供了一个简化版的Delegate:甚至在Model/View框架的使用中,提供了默认的委托,让这个控制 ...

  10. lesson - 9 Linux系统软件包管理

    1. rpm工具rpm Redhat Package Manager, 设计理念是开放的,不仅仅是在RedHat平台上,在SUSE上也是可以使用的. rpm包名字构成由-和.分成了若干部分,如abrt ...