spring发送邮件(无附件情况)

今天参考了网上一些朋友的代码,写了一个spring发送邮件的小例子。写下这篇文章,作为备忘。

1 AttachmentMailSender.java
package gov.emergency.emercore.persistencedb.test.mail;

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

public class AttachmentMailSender{
private MailSender mailSender;
private SimpleMailMessage mailMessage;

public AttachmentMailSender(){
 
}

public SimpleMailMessage getMailMessage() {
   return mailMessage;
}

public void setMailMessage(SimpleMailMessage mailMessage) {
   this.mailMessage = mailMessage;
}

public MailSender getMailSender() {
   return mailSender;
}

public void setMailSender(MailSender mailSender) {
   this.mailSender = mailSender;
}
public void sendMail(){
   SimpleMailMessage message = new SimpleMailMessage(mailMessage);
   message.setText("test Spring Email");
 
   mailSender.send(message);
}

}


2 配置文件 mail.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "spring-beans.dtd" >
<beans>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
   <value>smtp.163.com</value>
</property>
<property name="javaMailProperties">
   <props>
     <!-- 如果要使用用户名和密码验证,这一步需要 -->
     <prop key="mail.smtp.auth">true</prop>
   </props>
</property>
<property name="username">
<value>邮箱登录名</value>
</property>
<property name="password">
<value>邮箱密码</value>
</property>
</bean>
<!-- 简单的message -->
<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="to">
<value>接收人的邮件地址</value>
</property>
<property name="from">
<value>发送者的邮箱地址</value>
</property>
<property name="subject"> <!-- Email 标题 -->
<value>A Spring Mail sender</value>
</property>
</bean>
<!-- 测试发送的类 -->
<bean id="testMailSender" class="gov.emergency.emercore.persistencedb.test.mail.AttachmentMailSender">
<property name="mailMessage">
<ref bean="mailMessage"/>
</property>
<property name="mailSender">
<ref bean="mailSender"/>
</property>
</bean>
</beans>

3 测试类 MailTest.java

package gov.emergency.emercore.persistencedb.test.mail;

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

public class MailTest {
public static void main(String[] args){
  ApplicationContext context = new ClassPathXmlApplicationContext("gov/emergency/emercore/persistencedb/test/mail/mail.xml");
AttachmentMailSender sender = (AttachmentMailSender)context.getBean("testMailSender");
  sender.sendMail();
   System.out.println("----------------------");
}
 
}


这样就ok了,运行一下测试程序,就能向目标邮件地址发送一封邮件。

你可能感兴趣的:(spring,xml,bean)