spring 框架发送 simpleMail email

在网上找了spring框架下发送email的例子,结果发现发生 533错误

553 authentication is required 

找了半天也没有发现实质解决的办法,偶然发现居然没有对message设置from熟悉,设置上后居然通过.

具体类如下:

package com.mailtest.pub;

import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SimpleMailSender extends org.springframework.mail.javamail.JavaMailSenderImpl{
 
 private String senderMail;
 
 
 public void send(String toMail,String subject,String mail){
  ApplicationContext context = new ClassPathXmlApplicationContext("mail.xml");
  SimpleMailSender sender = (SimpleMailSender) context.getBean("mailSender");
  if(sender != null){
   
   SimpleMailMessage msg = new SimpleMailMessage();
   msg.setTo(toMail);
   msg.setSubject(subject);
   msg.setText(mail);
   msg.setFrom(sender.getSenderMail());
   sender.send(msg);
   
  }
  
  
 }
 
 public static void main(String[] avgr){
  
  SimpleMailSender sender = new SimpleMailSender();
  sender.send("[email protected]", "java", "this is a test from spring.");
 }

 public String getSenderMail() {
  return senderMail;
 }

 public void setSenderMail(String senderMail) {
  this.senderMail = senderMail;
 }

}

对应的xml如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "spring-beans.dtd" >
<beans>
 <bean id="mailSender" class="com.mailtest.SimpleMailSender">
  <property name="host">
   <value>smtp.163.com</value>
  </property>
  
  <property name="javaMailProperties">
    <props>
      <!-- 如果要使用用户名和密码验证,这一步需要 -->
     <prop key="mail.smtp.auth">true</prop>
    </props>
  </property>
  
  <property name="senderMail">
   <value>[email protected]</value>
  </property>
  
  <property name="username">
  <value>test</value>
  </property>
  <property name="password">
  <value>test</value>
  </property>
 </bean>

</beans>

----------------

533 错误除了需要设置验证外,有的服务器还检测是否有from

 

 

你可能感兴趣的:(spring 框架发送 simpleMail email)