使用spring的JavaMailSender傳送郵件
步驟:
一:pom.xml
<!-- java郵件 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
二:mail.properties
mail.host=smtp.hsmdata.com
mail.username=**@hsmdata.com
mail.password=**
三:applicationContext.xml
<!--傳送郵件-->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}"></property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
<property name="username" value="${mail.username}"></property>
<property name="password" value="${mail.password}"></property>
</bean>
四: 使用
@Autowired private JavaMailSender mailSender; public void toEmail(SimpleMailMessage mail){ mailSender.send(mail); } String str = String.valueOf(Math.round(Math.random() * 1000000)); SimpleMailMessage mail = new SimpleMailMessage(); mail.setTo(email); mail.setFrom(PropertiesUtil.getProperty(PropertiesConstant.MAIL_USERNAME)); mail.setSubject("價值連城專案驗證郵件"); mail.setText("尊敬的使用者:您好,感謝您使用價值連城專案,您的驗證碼為" + str + "。");