Springboot JavaMailSender发送邮件,Springboot整合Email,Springboot发送邮件封装

Springboot JavaMailSender发送邮件,Springboot整合Email,Springboot发送邮件封装

================================

©Copyright 蕃薯耀 2020-08-31

https://www.cnblogs.com/fanshuyao/

通过163邮件,向QQ邮件发送邮件,包括多邮件同时发送、附件、抄送、密送功能

一、引入Jar包依赖

pom.xml文件

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

二、application.properties文件配置

#POP3服务器: pop.163.com
#SMTP服务器: smtp.163.com
#IMAP服务器: imap.163.com
spring.mail.host=smtp.163.com
spring.mail.username=xxx@163.com
#spring.mail.from不支持中文,需要中文,看mail.properties
spring.mail.password=密码,通过开启SMTP获取密码
#465或者994
spring.mail.properties.mail.smtp.port: 465
spring.mail.properties.mail.smtp.ssl.enable: true
spring.mail.default-encoding=UTF-8

三、mail.properties文件配置

email.from.name=公司内部邮件

四、MailService

import javax.mail.MessagingException;

import org.springframework.mail.javamail.MimeMessageHelper;

public interface MailService {

    void handleAttachments(MimeMessageHelper mimeMessageHelper, String subject, String[] attachmentFilePaths);

    
    /**
         * 发送附件
    * @param subject 邮件主题
    * @param content 邮件内容
    * @param toEmails 接收的邮箱
    * @param ccPeoples 抄送人
    * @param bccPeoples 密送人,就是发送人和抄送人那里都不显示该收件人,但能收到邮件。
    * @param attachmentFilePaths 附件
    * @throws MessagingException
    */
    void send(String subject, String content, String[] toEmails, String[] ccPeoples,
            String[] bccPeoples, String[] attachmentFilePaths) throws MessagingException;

    
    /**
         * 发送附件
    * @param subject String 邮件主题
    * @param content String 邮件内容
    * @param toEmails String[] 接收的邮箱
    */
    void send(String subject, String content, String[] toEmails) throws MessagingException;

    
    /**
         * 发送附件
    * @param subject String 邮件主题
    * @param content String 邮件内容
    * @param toEmails String[] 接收的邮箱
    * @param attachmentFilePaths String[] 附件
    * <li>new String[] {"F:\0desk\邮件文档哦.pdf", "F:\0desk\maven-jar-plugin.txt"}</li>
    * @throws MessagingException
    */
    void send(String subject, String content, String[] toEmails, String[] attachmentFilePaths)
            throws MessagingException;

}

五、MailServiceImpl文件

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

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.context.annotation.PropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.lqy.mail.service.MailService;

@Service
@PropertySource(value="classpath:mail.properties", encoding="utf-8", ignoreResourceNotFound = true)
public class MailServiceImpl implements MailService{

     private final Logger log = LoggerFactory.getLogger(MailServiceImpl.class);
     
     @Value("${spring.mail.default-encoding}")
    public String defaultEncoding;

    /**
     * Spring Boot 提供了一个发送邮件的简单抽象,使用的是下面这个接口,这里直接注入即可使用
     */
    @Autowired
    private JavaMailSender mailSender;

    @Value(value = "${spring.mail.username}")
    private String username;
    
    @Value(value = "${email.from.name}")
    private String emailFromName;

    
    /**
             * 处理附件
     */
    @Override
    public void handleAttachments(MimeMessageHelper mimeMessageHelper, String subject, String[] attachmentFilePaths){
        //判断是否需要处理邮件的附件
        if(attachmentFilePaths != null && attachmentFilePaths.length > 0) {
            FileSystemResource resource;
            String fileName;
            //循环处理邮件的附件
            for (String attachmentFilePath : attachmentFilePaths) {
                //获取该路径所对应的文件资源对象
                resource = new FileSystemResource(new File(attachmentFilePath));
                //判断该资源是否存在,当不存在时仅仅会打印一条警告日志,不会中断处理程序。
                // 也就是说在附件出现异常的情况下,邮件是可以正常发送的,所以请确定你发送的邮件附件在本机存在
                if (!resource.exists()) {
                    log.warn("邮件->{} 的附件->{} 不存在!", subject, attachmentFilePath);
                    //开启下一个资源的处理
                    throw new RuntimeException("邮件需要发送的附件不存在。");
                }
                //获取资源的名称
                fileName = resource.getFilename();
                try {
                    //添加附件
                    mimeMessageHelper.addAttachment(fileName, resource);
                } catch (MessagingException e) {
                    e.printStackTrace();
                    log.error("邮件->{} 添加附件->{} 出现异常->{}", subject, attachmentFilePath, e.getMessage());
                }
            }
        }
    }
    
    
    /**
             * 发送附件
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param toEmails 接收的邮箱
     * @param ccPeoples 抄送人
     * @param bccPeoples 密送人,就是发送人和抄送人那里都不显示该收件人,但能收到邮件。
     * @param attachmentFilePaths 附件
     * @throws MessagingException
     */
    @Override
    public void send(String subject, String content, 
            String[] toEmails, String[] ccPeoples, String[] bccPeoples, 
            String[] attachmentFilePaths) throws MessagingException {
        //附件处理需要进行二进制传输
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, defaultEncoding);
        
        //设置发件人
        log.info("emailFromName = " + emailFromName);
        //log.info("from = " + from);
        mimeMessageHelper.setFrom(emailFromName + "<"+ username + ">");
        
        //设置邮件的主题
        log.info("subject = " + subject);
        mimeMessageHelper.setSubject(subject);
        
        //设置邮件的内容,区别是否是HTML邮件
        mimeMessageHelper.setText(content, true);//所有都以html格式发送
        
        //设置邮件的收件人
        log.info("toEmails = " + toEmails);
        mimeMessageHelper.setTo(toEmails);
        
        if(ccPeoples != null && ccPeoples.length > 0) {
            //设置邮件的抄送人
            mimeMessageHelper.setCc(ccPeoples);
        }

        if(bccPeoples != null && bccPeoples.length > 0) {
            //设置邮件的密送人
            mimeMessageHelper.setBcc(bccPeoples);
        }
        
        if(attachmentFilePaths != null && attachmentFilePaths.length > 0) {
            handleAttachments(mimeMessageHelper, subject, attachmentFilePaths);
        }
        
        mailSender.send(mimeMessage);
    }
    
    /**
         * 发送附件
    * @param subject String 邮件主题
    * @param content String 邮件内容
    * @param toEmails String[] 接收的邮箱
    */
    @Override
    public void send(String subject, String content, String[] toEmails) throws MessagingException {
        
        this.send(subject, content, toEmails, null, null, null);
        
    }
    
    
    /**
         * 发送附件
    * @param subject String 邮件主题
    * @param content String 邮件内容
    * @param toEmails String[] 接收的邮箱
    * @param attachmentFilePaths String[] 附件
    * @throws MessagingException
    */
    @Override
    public void send(String subject, String content, String[] toEmails, String[] attachmentFilePaths) throws MessagingException {
        
        this.send(subject, content, toEmails, null, null, attachmentFilePaths);
        
    }
    
    
    

}

六、发送邮件,示例代码:

@RequestMapping("/send4")
    public String send4(HttpServletRequest req, HttpServletResponse res) throws MessagingException {
        
        mailService.send("会议通知", "邮件内容,可以是html内容", 
                new String[] {"123456@qq.com", "147258@qq.com"}, new String[] {"F:\0desk\邮件文档哦.pdf", "F:\0desk\maven-jar-plugin.txt"});
        return "success";
    }

七、效果

(如果你觉得文章对你有帮助,欢迎捐赠,^_^,谢谢!) 

================================

©Copyright 蕃薯耀 2020-08-31

https://www.cnblogs.com/fanshuyao/

原文地址:https://www.cnblogs.com/fanshuyao/p/13590600.html