spring邮箱服务

  spring支持Java Mail的封装,邮件发送服务是由Spring的org.springframework.mail.MailSender接口。
  163邮件无法发送,qq邮箱可以发送,在第一次使用时系统会提示你开启POP3和SMTP协议。
  在spring项目环境下,首先到导入activation.jar和mail.jar 两个jar包;

SendMail.java(主程序)
public class SendMail {

public ApplicationContext ctx = null;


public SendMail() {
// 获取上下文
ctx = new ClassPathXmlApplicationContext("simplemail.xml");
}

public void send() {

// 获取JavaMailSender bean
JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");
JavaMailSenderImpl senderImpl = (JavaMailSenderImpl) ctx.getBean("javaMailSenderImpl");;

// 建立邮件信息
MimeMessage mailMessage = senderImpl.createMimeMessage();

try {
// 设置utf-8或GBK编码,否则邮件会有乱码
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");
messageHelper.setTo("[email protected]");// 接受者
messageHelper.setFrom("[email protected]");// 发送者
messageHelper.setSubject("测试邮件");// 主题

// 邮件内容,注意加参数true,表示启用html格式
messageHelper.setText("测试123", true);
sender.send(mailMessage);

} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
new SendMail().send();


}

}


  src目录下创建simplemail.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

         <!--spring 外在化应用 properties 参数的配置 -->
<context:property-placeholder location="/mail.properties" />

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}"></property>
<property name="port" value="${mail.port}"></property>
<property name="username" value="${mail.username}"></property>
<property name="password" value="${mail.password}"></property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.debug">false</prop>
<prop key="mail.smtp.socketFactory.class">${mail.smtp.socketFactory.class}</prop>
</props>
</property>
</bean>

<bean id="javaMailSenderImpl" class="org.springframework.mail.javamail.JavaMailSenderImpl"></bean>

</beans>

在src目录下创建mail.protertiesmail.host=smtp.qq.com
mail.port=465
mail.username=258778983
mail.password=你的密码
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory



你可能感兴趣的:(spring)