spring邮件发送,可发附件,可发多人

java代码:

  

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class SendMail {
 private JavaMailSender sender;

 public void sendMessage(String[] to, String from, String subject) throws MessagingException {
  MimeMessage msg = sender.createMimeMessage();
  MimeMessageHelper helper = new MimeMessageHelper(msg, true, "GB2312");

  helper.setTo(to);
  helper.setFrom(from);
  helper.setSubject(subject);

  helper.setText("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body><h1><a href='#'>郁闷!"
    + "</body></html>", true);

  // add the rar file
  FileSystemResource rarfile = new FileSystemResource(new File("D:/workspace/netbar-dw/src/netbar/dw/util/SendMail.java"));
  helper.addAttachment("SendMail.java", rarfile);

  sender.send(msg);
 }

 public JavaMailSender getSender() {
  return sender;
 }

 public void setSender(JavaMailSender sender) {
  this.sender = sender;
 }
 public static void main(String[] args) throws MessagingException {
  ApplicationContext context=new ClassPathXmlApplicationContext("spring-mail.xml");
  SendMail send=(SendMail) context.getBean("sendMail");
  String [] to={"[email protected]","[email protected]"};
  send.sendMessage(to,"[email protected]", "test");
 }
}

 

  

配置文件:

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

 <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <property name="host" value="mail.123.com">
  </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="[email protected]">
  </property>
  <property name="password" value="123">
  </property>
 </bean>
 <bean id="sendMail" class="netbar.dw.util.SendMail">
  <property name="sender" ref="mailSender"></property>
 </bean>
</beans>

 

 

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