javamail

ZHOU_VIP發表於2018-08-11

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>

 

相關文章