1.spring.xml配置
2.Controller层
3.Service接口
4.接口的实现类
因为要邮件要带附件,所以SimpleMailMessage不能用,要换成的MimeMessage
参考的演示
1) 引入jar包
2) spring配置文件中初始化mail sender
<bean name="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>smtp.sina.com</value>
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.starttls.required">true</prop>
</props>
</property>
<property name="username">
<value>XXX@sina.com</value>
</property>
<property name="password">
<value>XXX</value>
</property>
</bean>
3) 代码使用
@Component
public class XXX
@Autowired
protected JavaMailSender sender;
//发送邮件
@Override
public void sendMail(SimpleMailMessage message) throws Exception {
sender.send(message);
}
//构建邮件对象
@Override
public SimpleMailMessage buildSimpleMessage(AlarmData alarmData, AlarmForward forward) {
logger.info("buildSimpleMessage, forwardrule={}", forward);
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(forward.getEmailaddr().split(","));
message.setSubject(forward.getTitle());
message.setText("设备:" + alarmData.getDeveui() + " 上报告警,请及时处理!");
return message;
}
补充:
本机测试的环境不是阿里云环境,没有设置端口号(好像默认的端口号为25),测试可以发送邮件,
但阿里云环境要有端口号,加上端口号587
<property name="port">
<value>587</value>
</property>
<bean name="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>smtp.sina.com</value>
</property>
<property name="port">
<value>587</value>
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.starttls.required">true</prop>
</props>
</property>
<property name="username">
<value>XXX@sina.com</value>
</property>
<property name="password">
<value>XXX</value>
</property>
</bean>