欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java通过Spring配置发送QQ邮件

程序员文章站 2022-03-30 13:45:19
...
Java通过Spring配置发送QQ邮件:



1, 通过Maven依赖相关Jar包

<dependency>
     <groupId>javax.mail</groupId>
     <artifactId>mail</artifactId>
     <version>1.4</version>
</dependency>
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2, Spring配置
2.1, 添加mail.properties文件, 并让加载该文件到Spring容器

mail.host=smtp.qq.com
mail.port=587
[email protected]
mail.password=xxxx

2.2, 添加Spring.xml配置(这里也可以使用Spring java Connfig 配置)

<!-- 申明JavaMailSenderImpl对象 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	<property name="defaultEncoding" value="UTF-8" />
	<property name="host" value="${mail.host}" />
	<property name="port" value="${mail.port}"/>
	<property name="username" value="${mail.username}" />
	<property name="password" value="${mail.password}" />
	<property name="javaMailProperties">
		<props>
			<prop key="mail.smtp.auth">true</prop>
			<prop key="mail.debug">false</prop>
			<prop key="mail.smtp.timeout">5000</prop>
		</props>
	</property>
</bean>


3, Java使用
@Autowired
private MailSender mailSender;
 
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom("[email protected]");
mailMessage.setSubject("你好");
mailMessage.setText("这个是一个通过Spring框架来发送邮件的小程序");
mailMessage.setTo("[email protected]");
mailSender.send(mailMessage);

原:https://blog.csdn.net/a294039255/article/details/64122903