使用Spring的MailSender傳送郵件

小雷FansUnion發表於2016-02-24

第1步:掃描郵件傳送的屬性配置

<context:property-placeholder location="/config/mail.properties" ignore-unresolvable="true" />

mail.properties

mailServerHost=your host
mailServerPort=25
mailUserName= your name
mailPassword= your password
mailFromAddress= xijinping@china.com


第2步:配置bean
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>${mailServerHost}</value>
</property>
<property name="port">
<value>${mailServerPort}</value>
</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>${mailUserName}</value> <!-- 傳送者使用者名稱 -->
</property>
<property name="password">
<value>${mailPassword}</value> <!-- 傳送者密碼 -->
</property>
<!-- <property name="from">
 <value>${mailFromAddress}</value>
</property> -->

</bean>

第3步:注入bean

@Service
public class MailService {


@Resource
private JavaMailSender mailSender;

@Value("${mailFromAddress}")
private String mailFromAddress;

public void send(String subject,String content,String to){
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(content);
simpleMailMessage.setFrom(mailFromAddress);
simpleMailMessage.setTo(to);
mailSender.send(simpleMailMessage);
}
}


第4步:呼叫API傳送

mailService.send();


注意事項:

需要特別注意,userName是用來連線伺服器的,from引數是可以手動設定的。
from和userName可以不同。

from引數也是必須的,通過@Value註解注入到Java程式碼中。

相關文章