Java教程

JavaMail实现邮件发送

本文主要是介绍JavaMail实现邮件发送,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

SMTP服务器地址:一般是 smtp.xxx.com,比如163邮箱是smtp.163.com,qq邮箱是smtp.qq.com。

SMTP协议

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

POP3协议

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

二、Java发送邮件在这里插入图片描述
代码:
① .yml配置文件

  spring:
	 mail:
	   host: smtp.163.com
	   password: TZPVAGGRPGOGYSJS
	   username: c2483173886@163.com
	   port:
	   default-encoding: UTF-8
	   protocol: smtp
	   properties:
	     mail.smtp.auth: true
	     mail.smtp.starttls.enable: true
	     mail.smtp.starttls.required: true
	     mail.smtp.socketFactory.port: 465
	     mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
	     mail.smtp.socketFactory.fallback: false

② .SenEmailController

/**
 * @Author: ycw
 * @Description: TODO
 * @DateTime: 2021/9/13 15:53
 **/
@RestController
@Slf4j
@CrossOrigin(allowCredentials = "true")
@RequestMapping("/senMail")
public class SenEmailController {

@Autowired
private UploadDownloadUtils uploadAndDownload;
@Autowired
private ISendEmailService iSendEmailService;

    @ApiOperation(value = "邮件")
    @RecordLog(value = "发邮件",operateType = 2)
    @PostMapping
    public R senMail(@RequestParam("email") String email,
                     @RequestParam("subject") String subject,
                     @RequestParam("text") String text,
                     @RequestParam("file") MultipartFile file){
        Map<String, Object> map = uploadAndDownload.fileUploads(file);
        if(CollectionUtils.isEmpty(map)){
            throw new ExException(2001,"附件上传失败!");
        }
        Boolean senResult = false;
        senResult = iSendEmailService.sendAttachmentMail(email,subject,text,map);
        if (senResult){
            return R.ok();
        }
        return R.error();
    }
}

③ .ISendEmailService

/**
 * @Author: ycw
 * @Description: TODO
 * @DateTime: 2021/9/13 13:16
 **/
public interface ISendEmailService {
    //简单邮件
    boolean sendEmail();
    //定时发送带附件邮件
    Boolean sendAttachmentMail(Map<String,Object> map);
    //发送带附件的复杂的邮件
    boolean sendAttachmentMail(String email, String subject ,String text, Map<String,Object> map);
}

④ .ISendEmailService

/**
 * @Author: ycw
 * @Description: TODO
 * @DateTime: 2021/9/13 13:17
 **/
@Service
@Slf4j
public class ISendEmailServiceImpl implements ISendEmailService {
    @Value("${file.save-file-path}")
    private String saveFilePath;

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

    @Autowired
    private JavaMailSender mailSender;
    //注入spring发送邮件的对象
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public boolean sendEmail() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //目标邮箱
        simpleMailMessage.setTo("c2483173886@163.com");
        simpleMailMessage.setFrom(fromEmail);
        //主题
        simpleMailMessage.setSubject("测试");
        simpleMailMessage.setText("utf-8");
        try {
            javaMailSender.send(simpleMailMessage);        //执行发送
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean sendAttachmentMail(Map<String, Object> map) {
        if (!CollectionUtils.isEmpty(map)){
            for (Map.Entry entryMap : map.entrySet()) {
                try {
                    //邮件对象
                    MimeMessage mimeMessage = mailSender.createMimeMessage();
                    //解决中文名乱码
                    System.setProperty("mail.mime.splitlongparameters", "false");
                    //邮件处理对象
                    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");

                    //发件人
                    helper.setFrom(fromEmail);

                    //收件人
                    helper.setTo((String) entryMap.getKey());

                    //主题
                    helper.setSubject("hello!");

                    //文本内容
                    helper.setText("当月经营指导书和报表!", false);

                    //设置文件资源
                    helper.addAttachment((String) entryMap.getValue(), new File(saveFilePath+entryMap.getValue()));
                    //发送
                    mailSender.send(mimeMessage);

                    log.info("单附件邮件发送成功!");
                } catch (MessagingException e) {
                    log.error("单附件邮件发送失败:{}", e);
                    continue;
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean  sendAttachmentMail(String email, String subject ,String text, Map<String,Object> map){
        String saveFilePath = "saveFilePath";
        String fileName = "fileName";
        try {
            //邮件对象
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //解决中文名乱码
            System.setProperty("mail.mime.splitlongparameters", "false");
            //邮件处理对象
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");

            //发件人
            helper.setFrom(fromEmail);

            //收件人
            helper.setTo(email);

            //主题
            helper.setSubject(subject);

            //文本内容
            helper.setText(text,false);

            //设置文件资源
            helper.addAttachment((String) map.get(fileName), new File((String) map.get(saveFilePath)));
            System.out.println(fileName);
            //发送
            mailSender.send(mimeMessage);
            log.info("【单附件邮件发送成功】收件人:{} 主题:{} 文本内容:{} 文件路径:{}",email,text,text);
        } catch (MessagingException e) {
            log.error("单附件邮件发送失败:{}",e);
            return false;
        }
        return true;
    }
}

这篇关于JavaMail实现邮件发送的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!