springboot javamail_spring boot入门

springboot javamail_spring boot入门一、导入相关依赖在springboot中配置MultipartResolver注:使用了Spring的MultipartFile来接受文件上传才要配置的二、controller(service)

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

一、导入相关依赖

<!--邮件发送-->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.5</version>
</dependency>

在springboot中配置MultipartResolver

注:使用了Spring的MultipartFile来接受文件上传才要配置的

//配置文件上传
@Bean(name = "multipartResolver")
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setDefaultEncoding("UTF-8");
    // resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常
    resolver.setResolveLazily(true);
    resolver.setMaxInMemorySize(40960);
    // 上传文件大小 5G
    resolver.setMaxUploadSize(5 * 1024 * 1024 * 1024);
    return resolver;
}

二、controller(service)

这里的接口接收的字符串格式为[xxxxx@qq.com;xxxxx@163.com]这样的,入参的形式随意,最后调用工具类传入数组即可

import com.sanyu.tender.util.mailSend.MailSend;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:huang
 * @Date:2019-09-18 18:55
 * @Description:邮件发送接口
 */
@Controller
public class sendMailController {

    @Autowired
    private MailSend mailSend;

    @RequestMapping("/mail_send_show")
    public String showSendMail(){
        return "mail-send";
    }

    //接受文件上传
    @RequestMapping("/mail_send")
    @ResponseBody
    public Map sendMail(String title,String content,String email,MultipartFile file){
        Map<String,Object> map = new HashMap<>(16);

        //获取地址字符串并截取放入集合
        ArrayList<String> list = new ArrayList<>();
        String[] emailArr = email.split(";");
        for (int i = 1;i<emailArr.length;i++){
            list.add(emailArr[i]);
        }

        map.put("status","success");
        try {
            //调用javaMail邮件发送工具类
            mailSend.send(list,title,content,file);
        }catch (Exception e){
            e.getStackTrace();
            map.put("status","false");
        }
        return map;
    }

}

三、javaMail邮件发送工具类代码

/**
 * @Author:huang
 * @Date:2019-09-17 20:29
 * @Description:邮件发送工具类
 */
@Component
public final class MailSend {

    //发件人账号和授权码
    private static final String MY_EMAIL_ACCOUNT = "xxxx@163.com";
    private static final String MY_EMAIL_PASSWORD = "xxxx";

    //SMTP服务器(这里用的163 SMTP服务器)
    private static final String MEAIL_163_SMTP_HOST = "smtp.163.com";

    //端口号
    private static final String SMTP_163_PORT = "25";

    //message对象
    private MimeMessage message;

    {
        //创建发件邮箱对象
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", MEAIL_163_SMTP_HOST);
        properties.setProperty("mail.smtp.port", SMTP_163_PORT);
        properties.setProperty("mail.smtp.socketFactory.port", SMTP_163_PORT);
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.socketFactory.class", "SSL_FACTORY");
        //登录
        Session session = Session.getInstance(properties, new Authenticator() {
            // 设置认证账户信息
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MY_EMAIL_ACCOUNT, MY_EMAIL_PASSWORD);
            }
        });
        session.setDebug(false);

        //创建邮件对象
        System.out.println("创建发件人邮箱");
        message = new MimeMessage(session);
    }

    /**
     * 发送邮件
     * @param to 收件人邮箱的集合
     * @param title 邮件标题
     * @param content 邮件内容
     * @param file 通过表单上传的MultipartFile文件
     * @return 根据方法执行情况返回一个Boolean类型的值
     */
    public boolean send(ArrayList<String> to, String title, String content,MultipartFile file){
        File tempFile = null;

        try {
            //发件人
            message.setFrom(new InternetAddress(MY_EMAIL_ACCOUNT));
            //收件人
            setAccepter(to);
            //标题
            message.setSubject(title);

            //当存在附件的情况下,内容将和附件一起上传
            if (file != null){
                //添加附件和内容
                tempFile = getFile(file);
                setMultipartAndContent(tempFile,content);
            }else {
                //内容
                message.setContent(content, "text/html;charset=UTF-8");
            }

            //发送时间
            message.setSentDate(new Date());
            message.saveChanges();
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

        //发送邮件
        System.out.println("准备发送");
        try {
            Transport.send(message);

            //当存在附件的情况下发送完邮件以后删除上传到服务器的文件
            if (file != null){
                deleteServerFile(tempFile);
            }

        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送失败");
            return false;
        }
        System.out.println("发送完成");
        return true;
    }

    /**
     * 添加收件人
     * @param list 存放收件人邮箱的集合
     */
    private void setAccepter(ArrayList<String> list){
        //创建收件人地址数组
        InternetAddress[] sendTo = new InternetAddress[list.size()];
        //把list中的数据转至数组
        for (int i = 0; i < list.size(); i++) {
            //System.out.println("发送到:" + list.get(i));
            try {
                sendTo[i] = new InternetAddress(list.get(i));
            } catch (AddressException e) {
                e.printStackTrace();
                return;
            }
        }
        //填入message对象
        try {
            message.setRecipients(MimeMessage.RecipientType.TO,sendTo);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置附件和内容(当存在附件的情况下,必须通过此方法以发送内容,否则只显示附件而不显示内容)
     * @param file 要添加到message对象的文件
     * @param content 要添加到message对象的内容
     */
    private void setMultipartAndContent(File file,String content) {
        // 一个Multipart对象包含一个或多个BodyPart对象,来组成邮件的正文部分(包括附件)。
        MimeMultipart multiPart = new MimeMultipart();

        //内容模块
        MimeBodyPart partText = new MimeBodyPart();
        // 文件模块
        MimeBodyPart partFile = new MimeBodyPart();
        try {
            //添加内容
            partText.setContent(content,"text/html;charset=UTF-8");
            //添加文件
            partFile.attachFile(file);
            // 设置在收件箱中和附件名 并进行编码以防止中文乱码
            partFile.setFileName(MimeUtility.encodeText(file.getName()));

            multiPart.addBodyPart(partText);
            multiPart.addBodyPart(partFile);
            message.setContent(multiPart);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    /**
     * 将通过表单上传的MultipartFile文件上传到服务器并转换为File
     * @param file 通过表单上传的MultipartFile文件
     * @return 返回上传到服务器并转换完成的文件
     */
    private File getFile(MultipartFile file){
        //得到MultipartFile文件
        MultipartFile multipartFile = file;
        File f = null;

        //创建文件
        System.out.println("上传文件:"+multipartFile.getOriginalFilename());
        f = new File(multipartFile.getOriginalFilename());

        //得到文件流。以文件流的方式输出到新文件
        try (InputStream in  = multipartFile.getInputStream(); OutputStream os = new FileOutputStream(f)){
            // 可以使用byte[] ss = multipartFile.getBytes();代替while
            int n;
            byte[] buffer = new byte[4096];
            while ((n = in.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            BufferedReader bufferedReader = new BufferedReader(new FileReader(f));
            bufferedReader.close();
        }catch (IOException e){
            e.printStackTrace();
        }

        //输出file的URL
        try {
            System.out.println(f.toURI().toURL().toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        //输出文件的绝对路径
        System.out.println(f.getAbsolutePath());

        return new File(f.toURI());
    }

    /**
     * 删除文件
     * @param file 要删除的文件
     * @return 根据方法执行情况返回一个Boolean类型的值
     */
    private boolean deleteServerFile(File file){
        return file.delete();
    }

}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/170833.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • CAS算法的理解及应用「建议收藏」

    CAS算法的理解及应用「建议收藏」应用原子操作类,例如AtomicInteger,AtomicBoolean …适用于并发量较小,多cpu情况下;Java中有许多线程安全类,比如线程安全的集合类。从Java5开始,在java.util.concurrent包下提供了大量支持高效并发访问的集合接口和实现类。如:ConcurrentMap、ConcurrentLinkedQueue等线程安全集合。引入问题那么问题来了,这些线程安全类的底层是怎么保证线程安全的,你可能会想到是不是使用同步代码锁synchronized?引入概念这些线

    2022年8月9日
    8
  • 国际标准时间哪个时区_北京时间与世界时间的换算

    国际标准时间哪个时区_北京时间与世界时间的换算关于时间格式2016-08-9T10:01:54.123Z20160809100154.123Z处理方法今天遇到了一个奇怪的时间格式如以下格式,下面两种时间格式所表示的时间是同一个时间,这个不难理解//UTC时间,世界标准时间2016-08-9T10:01:54.123Z20160809100154.123Z如图所示,这是一张由网友提供的图片,里面显示的是时间UTC…

    2025年8月21日
    3
  • Idea激活码教程,永久有效激活码2024.3.5绝对有效2024.3.5

    Idea激活码教程,永久有效激活码2024.3.5绝对有效2024.3.5Idea 激活码教程永久有效 2024 3 5 激活码教程 Windows 版永久激活 持续更新 Idea 激活码 2024 3 5 成功激活

    2025年5月21日
    7
  • vue组件化的理解_vue组件化开发

    vue组件化的理解_vue组件化开发前言有时候有一组html结构的代码,并且这个上面可能还绑定了事件。然后这段代码可能有多个地方都被使用到了,如果都是拷贝来拷贝去,很多代码都是重复的,包括事件部分的代码都是重复的。那么这时候我们就可以

    2022年7月31日
    5
  • mac idea 2021.4.1 激活码_通用破解码

    mac idea 2021.4.1 激活码_通用破解码,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月17日
    44
  • Socket.io.js文件下载

    Socket.io.js文件下载想不通,现在什么文件在CSDN都需要用积分来说话了…麻木了…

    2025年7月21日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号