第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
<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代码中。