Java发送邮件(图片、附件、HTML)


使用邮件的一个小项目:定时邮件服务(发送考研词汇)



一、简介

要在网络上实现邮件功能,必须要有专门的邮件服务器。这些邮件服务器类似于现实生活中的邮局,它主要负责接收用户投递过来的邮件,并把邮件投递到邮件接收者的电子邮箱中。

SMTP服务器地址:

一般是 smtp.xxx.com,比如163邮箱是smtp.163.com,qq邮箱是smtp.qq.com。

SMTP协议:

通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器)。
163邮箱

POP3协议

通常把处理用户pop3请求(邮件接收请求)的服务器称之为POP3服务器(邮件接收服务器)。
QQ邮箱

二、邮箱服务授权配置

163邮箱在:设置—POP3中,打开相应的配置属性;

QQ邮箱:设置—账户安全中,打开相应的配置信息;

二、pom.xml依赖

   <!--邮件服务-->
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-mail</artifactId>
   </dependency>

   <dependency>
       <groupId>commons-net</groupId>
       <artifactId>commons-net</artifactId>
       <version>3.3</version>
   </dependency>

三、properties配置文件

#邮箱的账号(163邮箱)
spring.mail.host= smtp.163.com
spring.mail.username=comlydms@163.com
spring.mail.password=158143484fs
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.starttls.enable=true
spring.mail.properties.mail.starttls.required=true

四、发送普通邮件

1、web层代码

    /**
     * 测试普通邮件调用
     */
    @RequestMapping(value = "/simpleEmail", method = {RequestMethod.POST})
    public ApiResult sendSimpleEmail() {

        mailService.sendSimpleMail("395096666@qq.com", "这是一个测试邮件", "这是一个测试邮件");
        return ApiResult.succ("调用成功");
    }

2、Service代码

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String fromMail;

    /**
     * 发送普通邮件
     *
     * @param toMail  收件方
     * @param subject 标题
     * @param content 邮件内容
     */
    public void sendSimpleMail(String toMail, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(fromMail);
        simpleMailMessage.setTo(toMail);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        try {
            sender.send(simpleMailMessage);
            logger.info("发送给:{}简单邮件已经发送。 subject:{}", toMail, subject);
        } catch (Exception e) {
            logger.info("发送给:{}send mail error subject:{}", toMail, subject);
            e.printStackTrace();
        }
    }

二、发送Html格式邮件

1、Web层代码

   /**
     * 测试Html格式调用
     */
    @RequestMapping(value = "/htmlEmail", method = {RequestMethod.POST})
    public ApiResult sendHtmlEmail() {

//        1、拼接模拟的数据
        English english = new English();
        english.setEnglish("my");
        english.setChinese("我的");
        english.setCodechinese("自己的东西");
        ArrayList<English> en = new ArrayList<>();
        en.add(english);
        en.add(english);

//        2.1、写html开始内容
        String start = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title></title></head><body><font color=\"red\">定时发送</font><table border=\"1\"><tr><th>英文</th><th>标准注解</th><th>代码中注解</th></tr>";
//        2-2、表html中间内容
        String prime = "";
        for (int i = 0; i < en.size(); i++) {
            English english1 = en.get(i);
            String center = "<tr><td>English</td><td>Chinese</td><td>CodeChinese</td></tr>";
            String one = center.replaceFirst("English", english1.getEnglish());
            String two = one.replaceFirst("Chinese", english1.getChinese());
            String result = two.replaceFirst("CodeChinese", english1.getCodechinese());
            prime = prime + result;

        }
//        2-3、写html结尾内容
        String end = "</table></body></html>";
//        3、拼接html
        String html = start + prime + end;
//        4、发送邮件
        mailService.sendHtmlMail("395096666@qq.com", "定时邮件发送", html);

        return ApiResult.succ("调用成功");
    }

2、Service代码

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String fromMail;

    /**
     * 发送带Html格式邮件
     *
     * @param toMail  收件方
     * @param subject 标题
     * @param content 邮件内容
     */
    public void sendHtmlMail(String toMail, String subject, String content) {
//        1、封装数据
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setTo(toMail);
            mimeMessageHelper.setFrom(fromMail);
            mimeMessageHelper.setText(content, true);
            mimeMessageHelper.setSubject(subject);

//            2、发送邮件
            sender.send(mimeMessage);
            logger.info("发送给:{}html邮件已经发送。 subject:{}", toMail, subject);
        } catch (Exception e) {
            logger.info("发送给:{}html send mail error subject:{}", toMail, subject);
            e.printStackTrace();
        }
    }

三、发送Html带图片邮件

1、Web层代码

   /**
     * 测试Html带图片
     */
    @RequestMapping(value = "/htmlPotoEmail", method = {RequestMethod.POST})
    public ApiResult sendHtmlPoto() {
//        1、创建html格式的数据
        String html = "<!DOCTYPE html>\r\n" +
                "<html>\r\n" +
                "<head>\r\n" +
                "<meta charset=\"UTF-8\">\r\n" +
                "<title>Insert title here</title>" +
                "\r\n" +
                "</head>\r\n" +
                "<body>\r\n" +
                "<img src=\"cid:image1\"/> " +
                "<img src=\"cid:image2\"/> " +
                "	<font color=\"red\">发送html</font>\r\n" +
                "</body>\r\n" +
                "</html>";
//        2、封装html中的图片数据
        List<InlineResource> list = new ArrayList<>();
//        2-1获取图片的地址
        String path = WordSmsController.class.getClassLoader().getResource("image.jpg").getPath();
//        2-2、将图片的地址封装到实体类中
        InlineResource resource = new InlineResource("image1", path);
        InlineResource resource2 = new InlineResource("image2", path);
        list.add(resource2);
        list.add(resource);

//        3、发送邮件
        mailService.sendHtmlPhotoMail("395096666@qq.com", "这是一个测试邮件", html, list);

        return ApiResult.succ("调用成功");
    }

2、Service层代码

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String fromMail;

   /**
     * 发送静态资源(一般是图片)的邮件
     *
     * @param
     * @param subject
     * @param content 邮件内容,需要包括一个静态资源的id,比如:<img src=\"cid:image\" >
     * @param
     */
    public void sendHtmlPhotoMail(String to, String subject, String content, List<InlineResource> resourceist) {

//            1、编写发送的数据
        MimeMessage message = sender.createMimeMessage();
//            1-1、添加html数据
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(fromMail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
//                1-2、添加图片数据
            for (InlineResource inlineResource : resourceist) {
//                    图片的路径
                FileSystemResource res = new FileSystemResource(new File(inlineResource.getPath()));
//                    将html中的图片名称替换为相应的图片路径
                helper.addInline(inlineResource.getCid(), res);
            }

//                2、发送邮件
            sender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }

3、封装图片路径的实体类

避免代码看的太多,实体类只保留了使用。

public class InlineResource {

    private String cid;
    private String path;

    public InlineResource(String cid, String path) {
        this.cid = cid;
        this.path = path;
    }
}

四、发送带附件邮件

1、Web层代码

   /**
     * 测试附件调用
     */
    @RequestMapping(value = "/fileEmail", method = {RequestMethod.POST})
    public ApiResult sendFileEmail() {
//        1、写html格式内容
        String html = "<!DOCTYPE html>\r\n" +
                "<html>\r\n" +
                "<head>\r\n" +
                "<meta charset=\"UTF-8\">\r\n" +
                "<title>Insert title here</title>\r\n" +
                "</head>\r\n" +
                "<body>\r\n" +
                "	<font color=\"red\">发送html</font>\r\n" +
                "</body>\r\n" +
                "</html>";
//        2、获取图片所在的路径
        String path = WordSmsController.class.getClassLoader().getResource("image.jpg").getPath();
//        3、发送邮件
        mailService.sendFileMail("395096666@qq.com", "这是一个测试邮件", html, path);

        return ApiResult.succ("调用成功");
    }

2、Service层代码

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String fromMail;

  /**
     * 发送带附件邮件
     *
     * @param toMail
     * @param subject
     * @param content
     */
    public void sendFileMail(String toMail, String subject, String content, String filePath) {
//        1、编写发送的数据
        MimeMessage message = sender.createMimeMessage();
//        1-1、添加html数据
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(fromMail);
            helper.setTo(toMail);
            helper.setSubject(subject);
            helper.setText(content, true);
//            1-2、添加图片数据
//            获取图片数据
            FileSystemResource file = new FileSystemResource(new File(filePath));
//            获取图片的名称
            String fileName = filePath.substring(filePath.lastIndexOf("/"));
//            添加数据
            helper.addAttachment(fileName, file);

//            2、发送邮件
            sender.send(message);
            logger.info("发送给:{}带附件的邮件已经发送。",toMail);
        } catch (Exception e) {
            logger.error("发送给:{}带附件的邮件时发生异常!", toMail);
            e.printStackTrace();
        }
    }

八、完整代码

为了方便使用,把使用的代码都贴在下面

1、Web层代码

import com.lydms.common.ApiResult;
import com.lydms.pojo.English;
import com.lydms.pojo.InlineResource;
import com.lydms.utils.MailService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/email")
public class WordEmailController {
    private static final Logger logger = LogManager.getLogger(WordSmsController.class);

    @Autowired
    private MailService mailService;



    /**
     * 测试普通邮件调用
     */
    @RequestMapping(value = "/simpleEmail", method = {RequestMethod.POST})
    public ApiResult sendSimpleEmail() {

        mailService.sendSimpleMail("395096666@qq.com", "这是一个测试邮件", "这是一个测试邮件");

        return ApiResult.succ("调用成功");
    }

    /**
     * 测试Html格式调用
     */
    @RequestMapping(value = "/htmlEmail", method = {RequestMethod.POST})
    public ApiResult sendHtmlEmail() {

//        1、拼接模拟的数据
        English english = new English();
        english.setEnglish("my");
        english.setChinese("我的");
        english.setCodechinese("自己的东西");
        ArrayList<English> en = new ArrayList<>();
        en.add(english);
        en.add(english);

//        2.1、写html开始内容
        String start = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title></title></head><body><font color=\"red\">定时发送</font><table border=\"1\"><tr><th>英文</th><th>标准注解</th><th>代码中注解</th></tr>";
//        2-2、表html中间内容
        String prime = "";
        for (int i = 0; i < en.size(); i++) {
            English english1 = en.get(i);
            String center = "<tr><td>English</td><td>Chinese</td><td>CodeChinese</td></tr>";
            String one = center.replaceFirst("English", english1.getEnglish());
            String two = one.replaceFirst("Chinese", english1.getChinese());
            String result = two.replaceFirst("CodeChinese", english1.getCodechinese());
            prime = prime + result;

        }
//        2-3、写html结尾内容
        String end = "</table></body></html>";
//        3、拼接html
        String html = start + prime + end;
//        4、发送邮件
        mailService.sendHtmlMail("395096666@qq.com", "定时邮件发送", html);

        return ApiResult.succ("调用成功");
    }


    /**
     * 测试Html带图片
     */
    @RequestMapping(value = "/htmlPotoEmail", method = {RequestMethod.POST})
    public ApiResult sendHtmlPotoEmail() {
//        1、创建html格式的数据
        String html = "<!DOCTYPE html>\r\n" +
                "<html>\r\n" +
                "<head>\r\n" +
                "<meta charset=\"UTF-8\">\r\n" +
                "<title>Insert title here</title>" +
                "\r\n" +
                "</head>\r\n" +
                "<body>\r\n" +
                "<img src=\"cid:image1\"/> " +
                "<img src=\"cid:image2\"/> " +
                "	<font color=\"red\">发送html</font>\r\n" +
                "</body>\r\n" +
                "</html>";
//        2、封装html中的图片数据
        List<InlineResource> list = new ArrayList<>();
//        2-1获取图片的地址
        String path = WordSmsController.class.getClassLoader().getResource("image.jpg").getPath();
//        2-2、将图片的地址封装到实体类中
        InlineResource resource = new InlineResource("image1", path);
        InlineResource resource2 = new InlineResource("image2", path);
        list.add(resource2);
        list.add(resource);

//        3、发送邮件
        mailService.sendHtmlPhotoMail("395096666@qq.com", "这是一个测试邮件", html, list);

        return ApiResult.succ("调用成功");
    }


    /**
     * 测试附件调用
     */
    @RequestMapping(value = "/fileEmail", method = {RequestMethod.POST})
    public ApiResult sendFileEmail() {
//        1、写html格式内容
        String html = "<!DOCTYPE html>\r\n" +
                "<html>\r\n" +
                "<head>\r\n" +
                "<meta charset=\"UTF-8\">\r\n" +
                "<title>Insert title here</title>\r\n" +
                "</head>\r\n" +
                "<body>\r\n" +
                "	<font color=\"red\">发送html</font>\r\n" +
                "</body>\r\n" +
                "</html>";
//        2、获取图片所在的路径
        String path = WordSmsController.class.getClassLoader().getResource("image.jpg").getPath();
//        3、发送邮件
        mailService.sendFileMail("395096666@qq.com", "这是一个测试邮件", html, path);

        return ApiResult.succ("调用成功");
    }
}

2、Service层代码

import com.lydms.pojo.InlineResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

@Service
public class MailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String fromMail;

    /**
     * 发送普通邮件
     *
     * @param toMail  收件方
     * @param subject 标题
     * @param content 邮件内容
     */
    public void sendSimpleMail(String toMail, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(fromMail);
        simpleMailMessage.setTo(toMail);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        try {
            sender.send(simpleMailMessage);
            logger.info("发送给:{}简单邮件已经发送。 subject:{}", toMail, subject);
        } catch (Exception e) {
            logger.info("发送给:{}send mail error subject:{}", toMail, subject);
            e.printStackTrace();
        }
    }


    /**
     * 发送带Html格式邮件
     *
     * @param toMail  收件方
     * @param subject 标题
     * @param content 邮件内容
     */
    public void sendHtmlMail(String toMail, String subject, String content) {
//        1、封装数据
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setTo(toMail);
            mimeMessageHelper.setFrom(fromMail);
            mimeMessageHelper.setText(content, true);
            mimeMessageHelper.setSubject(subject);

//            2、发送邮件
            sender.send(mimeMessage);
            logger.info("发送给:{}html邮件已经发送。 subject:{}", toMail, subject);
        } catch (Exception e) {
            logger.info("发送给:{}html send mail error subject:{}", toMail, subject);
            e.printStackTrace();
        }
    }


    /**
     * 发送静态资源(一般是图片)的邮件
     *
     * @param
     * @param subject
     * @param content 邮件内容,需要包括一个静态资源的id,比如:<img src=\"cid:image\" >
     * @param
     */
    public void sendHtmlPhotoMail(String to, String subject, String content, List<InlineResource> resourceist) {

//            1、编写发送的数据
        MimeMessage message = sender.createMimeMessage();
//            1-1、添加html数据
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(fromMail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
//                1-2、添加图片数据
            for (InlineResource inlineResource : resourceist) {
//                    图片的路径
                FileSystemResource res = new FileSystemResource(new File(inlineResource.getPath()));
//                    将html中的图片名称替换为相应的图片路径
                helper.addInline(inlineResource.getCid(), res);
            }

//                2、发送邮件
            sender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }


    /**
     * 发送带附件邮件
     *
     * @param toMail
     * @param subject
     * @param content
     */
    public void sendFileMail(String toMail, String subject, String content, String filePath) {
//        1、编写发送的数据
        MimeMessage message = sender.createMimeMessage();
//        1-1、添加html数据
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(fromMail);
            helper.setTo(toMail);
            helper.setSubject(subject);
            helper.setText(content, true);
//            1-2、添加图片数据
//            获取图片数据
            FileSystemResource file = new FileSystemResource(new File(filePath));
//            获取图片的名称
            String fileName = filePath.substring(filePath.lastIndexOf("/"));
//            添加数据
            helper.addAttachment(fileName, file);

//            2、发送邮件
            sender.send(message);
            logger.info("发送给:{}带附件的邮件已经发送。",toMail);
        } catch (Exception e) {
            logger.error("发送给:{}带附件的邮件时发生异常!", toMail);
            e.printStackTrace();
        }
    }
}
posted @ 2019-12-30 15:30  ah_lydms  阅读(475)  评论(0编辑  收藏  举报