Springboot--Mail
package com.example.springbootmail.mail; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class EmailConfig { @Value("${spring.mail.username}") private String emailFrom; public String getEmailFrom() { return emailFrom; } public void setEmailFrom(String emailFrom) { this.emailFrom = emailFrom; } }
package com.example.springbootmail.controller; import com.example.springbootmail.service.EmailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller @RequestMapping("/users") public class UsersController { @Autowired private EmailService emailService; @RequestMapping("/sendMail") @ResponseBody public String findById(){ // emailService.sendsSimpleMail("zhouwuji@aliyun.com","hello","明天来我家玩"); emailService.sendsSimpleMail("1303379118@qq.com","hello","明天来我家玩"); return "success"; } @RequestMapping("/sendfileMail") @ResponseBody public String sendfileMail(){ // emailService.sendsSimpleMail("zhouwuji@aliyun.com","hello","明天来我家玩"); emailService.sendAttachmentsMail("1303379118@qq.com","hello","明天来我家玩","src\main\resources\static\20180210222920.xls"); return "success"; } }
service
package com.example.springbootmail.service; public interface EmailService { //发送简单的邮件 void sendsSimpleMail(String sendTo, String title, String content); void sendAttachmentsMail(String to, String subject, String content, String filePath); }
package com.example.springbootmail.service.impl; import com.example.springbootmail.mail.EmailConfig; import com.example.springbootmail.service.EmailService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; 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.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @Service public class EmailServiceImpl implements EmailService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private EmailConfig emailConfig; @Autowired private JavaMailSender mailSender; @Override public void sendAttachmentsMail(String to, String subject, String content, String filePath) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(emailConfig.getEmailFrom()); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1); //添加多个附件可以使用多条 helper.addAttachment(fileName, file) helper.addAttachment(fileName, file); mailSender.send(message); logger.info("带附件的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送带附件的邮件时发生异常!", e); } } @Override public void sendsSimpleMail(String sendTo, String title, String content) { //简单的邮件的发送 SimpleMailMessage message=new SimpleMailMessage(); message.setFrom(emailConfig.getEmailFrom()); message.setTo(sendTo); message.setSubject(title); message.setText(content); mailSender.send(message); } }
package com.example.springbootmail; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringbootMailApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMailApplication.class, args); } }
#配置log-back日志 logging.config=classpath:logback-boot.xml server.address=localhost server.port=8080 #配置javamail spring.mail.host=smtp.163.com spring.mail.port=25 spring.mail.username=17612187380@163.com # 授权码 spring.mail.password=OU7758521 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="false"> <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径--> <property name="LOG_HOME" value="D:/logs" /> <!-- 控制台输出 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符--> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> </encoder> </appender> <!-- 按照每天生成日志文件 --> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--日志文件输出的文件名--> <FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log</FileNamePattern> <!--日志文件保留天数--> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符--> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> </encoder> <!--日志文件最大的大小--> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> <!-- show parameters for hibernate sql 专为 Hibernate 定制 --> <logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" /> <logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" /> <logger name="org.hibernate.SQL" level="DEBUG" /> <logger name="org.hibernate.engine.QueryParameters" level="DEBUG" /> <logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" /> <!--myibatis log configure--> <logger name="com.apache.ibatis" level="TRACE"/> <logger name="java.sql.Connection" level="DEBUG"/> <logger name="java.sql.Statement" level="DEBUG"/> <logger name="java.sql.PreparedStatement" level="DEBUG"/> <!-- 日志输出级别 --> <root level="INFO"> <appender-ref ref="STDOUT" /> <appender-ref ref="FILE" /> </root> <!--日志异步到数据库 --> <!--<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">--> <!--<!–日志异步到数据库 –>--> <!--<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">--> <!--<!–连接池 –>--> <!--<dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">--> <!--<driverClass>com.mysql.jdbc.Driver</driverClass>--> <!--<url>jdbc:mysql://127.0.0.1:3306/databaseName</url>--> <!--<user>root</user>--> <!--<password>root</password>--> <!--</dataSource>--> <!--</connectionSource>--> <!--</appender>--> </configuration>
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>springboot-mail</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-mail</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <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-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>