今天给大家带来的是用java发送邮件,如有不足之处,敬请指教。
本次我们利用QQ来发送邮件。
一、配置步骤
- 打开邮箱的POP3、SMTP
- 导入包
- 配置邮件发送类
- 编写邮件
- 测试
二、配置流程
2.1 打开邮箱的POP3、SMTP
图示 |
---|
2.2 导入包
图示 |
---|
2.3 配置邮件发送类
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<context:component-scan base-package="com.xkt"></context:component-scan>
<!-- 配置邮件发送类 -->
<bean name="mailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl">
<!-- 指定邮件的编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 指定邮件的服务器 -->
<property name="host" value="smtp.qq.com"></property>
<!-- 指定发送人的邮箱 -->
<property name="username" value="这里填入邮箱账号"></property>
<!-- 指定发送人的密码 -->
<property name="password" value="这里填入邮箱授权的密码"></property>
<!-- 指定发送的邮箱服务器是需求认证的 -->
<property name="javaMailProperties">
<value>
mail.smtp.auth=true
</value>
</property>
</bean>
</beans>
2.4 邮件发送内容
package com.xkt.service;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
/**
* @author lzx
*
*/
@Service
public class MailService {
@Autowired
private MailSender mailSender;
/**
* 发送邮件
*/
public void send() {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo("这里填入要发送到的邮箱");
message.setText("Hello");
message.setSubject("title");
message.setFrom("******");
message.setSentDate(new Date());
mailSender.send(message);
}
}
2.5 测试代码
package com.xkt.test;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.xkt.service.MailService;
/**
* @author lzx
*
*/
public class MailServiceTest {
@Test
public void send() {
try {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:applicationContext.xml");
MailService mailService = context.getBean(MailService.class);
// 发送邮件
mailService.send();
context.close();
} catch (BeansException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
版权说明:欢迎以任何方式进行转载,但请在转载后注明出处!