Spring 使用163发邮件
Mail 发简单邮件
package cn.mail;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
/**
* 发简单邮件
* */
public class Mail {
//接口
private MailSender mailSender;//注入已经配置好参数的类
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
//发送
public void send(){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("[email protected]");//发件人
message.setTo("[email protected]");//收件人
message.setSubject("Spring 简单邮件");
message.setText("元旦快乐");
mailSender.send(message);
System.out.println("发送成功");
}
}
applicationContext.xml 配置
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- Spring 实现的发邮件的类 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.163.com" /><!-- 服务器 -->
<property name="port" value="25" /><!-- 端口 -->
<property name="username" value="[email protected]" /><!-- 用户名 -->
<property name="password" value="******" /><!-- 密码 -->
<property name="protocol" value="smtp" /><!-- 协议 -->
<property name="defaultEncoding" value="utf-8" /><!-- 默认编码 -->
<property name="javaMailProperties">
<props>
<!-- 设置 SMT 服务器需要用户验证 -->
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<!-- 简单邮件发送 -->
<bean id="mail" class="cn.mail.Mail" p:mailSender-ref="mailSender" />
</beans>
Test 测试数据
package cn.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.mail.Mail;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
/*测试简单邮件*/
Mail mail = (Mail) context.getBean("mail");
mail.send();
}
}
效果图: