利用 spring mail 通过 gmail(SSL) 发邮件
通过一般的邮件服务器 比如 163 网上有许多例子,但 gmail 要通过 SSL 才能发送。下面是针对 gmail 发送邮件的配置。
这是 gmail smtp 的配置,详见 http://mail.google.com/support/bin/answer.py?hl=zh-Hans&answer=13287
spring 的配置如下:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean name="mailSender" value="smtp.gmail.com"/> <property name="port" value="465"/> <property name="username" value="yourUserName@gmail.com"/> <property name="password" value="yourPassword"/> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> </props> </property> </bean></beans>
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");MailSender mailSender = context.getBean(MailSender.class);SimpleMailMessage mail = new SimpleMailMessage();mail.setFrom("yourUserName@gmail.com");mail.setTo("destination@163.com");mail.setSubject("测试spring Mail(Gmail)");mail.setText("hello,java");mailSender.send(mail);