1.spring配置
<!--邮件发送实现类-->
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.163.com"/>
<property name="port" value="25"/>
<property name="username" value="test@163.com"/>
<property name="password" value="test"/>
<property name="javaMailProperties">
<props >
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="test@163.com" /><!--发送人-->
<property name="subject" value="System" /><!--主题-->
</bean>
<!--线程池异步发送邮件-->
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="queueCapacity" value="25" />
</bean>
2.java工具类
@Component("mailSenderUtil")
public class MailSenderUtil {
@Resource
private JavaMailSender javaMailSender;
@Resource
private SimpleMailMessage simpleMailMessage;
@Resource
private TaskExecutor taskExecutor;
/**
* 构建邮件内容,发送邮件。
* @param email 收件人邮箱
* @param content 收件内容
*/
public void send(String email,String content) {
this.taskExecutor.execute(new SendMailThread(email,null,content));
}
//内部线程类,利用线程池异步发邮件。
private class SendMailThread implements Runnable {
private String to;
private String subject;
private String content;
private SendMailThread(String to, String subject, String content) {
super();
this.to = to;
this.subject = subject;
this.content = content;
}
@Override
public void run() {
sendMail(to, subject, content);
}
}
/**
* 发送邮件
* @param to 收件人邮箱
* @param subject 邮件主题
* @param content 邮件内容
*/
public void sendMail(String to, String subject, String content) {
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");
messageHelper.setFrom(simpleMailMessage.getFrom());
if (subject != null) {
messageHelper.setSubject(subject);
} else {
messageHelper.setSubject(simpleMailMessage.getSubject());
}
messageHelper.setTo(to);
messageHelper.setText(content, true);
javaMailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
3.方法调用
@resource
private MailSenderUtil mailSenderUtil;
...
mailSenderUtil.send("test@qq.com", "HelloWorld");