丄諦啲仇魜ヤ
          如 果 敵 人 讓 你 生 氣 , 那 說(shuō) 明 你 沒(méi) 有 勝 他 的 把 握!
          posts - 6,comments - 56,trackbacks - 1
          Spring提供了一個(gè)發(fā)送電子郵件的高級(jí)抽象層,它向用戶屏蔽了底層郵件系統(tǒng)的一些細(xì)節(jié),同時(shí)負(fù)責(zé)低層次的代表客戶端的資源處理。Spring郵件抽象層的主要包為org.springframework.mail。它包括了發(fā)送電子郵件的主要接口MailSender和 封裝了簡(jiǎn)單郵件的屬性如from, to,cc, subject, text的值對(duì)象叫做SimpleMailMessage。
          1、我們定義一個(gè)發(fā)送郵件的接口:OrderManager.java
          1 public interface OrderManager extends BaseManager{
          2 /**
          3 *email,要發(fā)送的郵件地址;
          4 *Code:激活碼
          5 */
          6      public void placeOrder(String email);
          7 }

          2、我們需要對(duì)該接口進(jìn)行實(shí)現(xiàn)的方法:OrderManagerImpl.java

           1 import javax.mail.Message;
           2 import javax.mail.MessagingException;
           3 import javax.mail.internet.InternetAddress;
           4 import javax.mail.internet.MimeMessage;
           5 import org.springframework.mail.MailException;
           6 import org.springframework.mail.javamail.JavaMailSender;
           7 import org.springframework.mail.javamail.MimeMessagePreparator;
           8 import service.OrderManager;
           9  
          11 public class OrderManagerImpl extends BaseManagerImpl implements OrderManager {
          12 
          13 private JavaMailSender mailsender;
          14 private MyMailMessage message;
          15 
          16 
          17     public void setMessage(CityMailMessage message)
          18     {
          19         this.message = message;
          20     }
          21     public void setMailsender(JavaMailSender mailsender) {
          22         this.mailsender = mailsender;
          23     }
          24     public void placeOrder(final String email) {
          25         
          26 
          27         MimeMessagePreparator preparator = new MimeMessagePreparator() {
          28             public void prepare(MimeMessage mimeMessage) throws MessagingException {
          29                 mimeMessage.setRecipient(Message.RecipientType.TO, 
          30                         new InternetAddress(email));
          31                 mimeMessage.setFrom(new InternetAddress(message.getFrom()));
          32                 /**轉(zhuǎn)換編碼為GBK*/
          33                 mimeMessage.setSubject(message.getSubject(),"GBK");
          36                 mimeMessage.setText(email+"<br>"+message.getSubject()+message.getText(),"GBK");
          37                 
          38             }
          39         };
          40         try{
          41             mailsender.send(preparator);
          42         }
          43         catch(MailException ex) {
          44             //log it and go on
          45             System.err.println(ex.getMessage());            
          46         }
          47     }
          48 }

          3、spring配置發(fā)送email的applicationContext-email.xml

           1 <?xml version="1.0" encoding="UTF-8"?>
           2 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
           3     "http://www.springframework.org/dtd/spring-beans.dtd">
           4 
           5 <beans>
           6     <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
           7         <property name="host">
           8             <value>smtp.163.com</value>
           9         </property>
          10         <property name="username">
          11             <value>username</value>
          12         </property>
          13         <property name="password">
          14             <value>password</value>
          15         </property>
          16         <property name="javaMailProperties">
          17             <props>
          18                 <prop key="mail.smtp.auth">true</prop>
          19                 <prop key="mail.smtp.timeout">25000</prop>
          20             </props>
          21         </property>
          22     </bean>
          23 
          24     <bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
          25         <property name="from">
          26             <value>Email</value>
          27         </property>
          28         <property name="subject">
          29             <value>標(biāo)題</value>
          30         </property>
          31         <property name="text">
          32             <value>內(nèi)容</value>
          33         </property>
          46     </bean>
          47 
          48     <bean id="orderManager" class="cn.cityyouth.service.impl.OrderManagerImpl">
          49         <property name="mailsender">
          50             <ref bean="mailSender" />
          51         </property>
          52         <property name="message">
          53             <ref bean="mailMessage" />
          54         </property>
          55     </bean>
          56 
          57 </beans>

          4、最后配置自己的jsp頁(yè)面以及action

           1 package cn.cityyouth.web.action;
           2 
           3 import javax.servlet.http.HttpServletRequest;
           4 import javax.servlet.http.HttpServletResponse;
           5 import org.apache.struts.action.ActionForm;
           6 import org.apache.struts.action.ActionForward;
           7 import org.apache.struts.action.ActionMapping;
           8 import org.apache.struts.action.ActionMessage;
           9 import org.apache.struts.action.ActionMessages;
          10 import com.test.service.OrderManager;
          11 
          12 public class SendMailAction extends BaseAction {
          13 
          14     /**
          15      * Method execute
          16      * 
          17      * @param mapping
          18      * @param form
          19      * @param request
          20      * @param response
          21      * @return ActionForward
          22      */
          23     public ActionForward execute(ActionMapping mapping, ActionForm form,
          24             HttpServletRequest request, HttpServletResponse response) {
          25         OrderManager omi=(OrderManager)this.getBean("orderManager");
          26         String useremail="123@163.com";
          27          omi.placeOrder(useremail);
          28        }
          29 }

          到此所有的開(kāi)發(fā)以結(jié)束。

          Sring郵件抽象層的主要包是:org.springframework.mail 包。它包含叫MailSender為發(fā)送郵件的核心接口和包含簡(jiǎn)單郵件屬性例如from,to,cc,subject,text叫SimpleMailMessage的值對(duì)象. 這個(gè)包也包含一個(gè)檢查異常的層次,它支持一個(gè)更高級(jí)別的抽象超過(guò)低級(jí)別的郵件系統(tǒng)異常伴隨根異常存在MailException. 請(qǐng)參考JavaDocs為更多的信息雜郵件異常層次。

          spring in action in action also provides a sub-interface of MailSender for specialized JavaMail features such as MIME messages, namely org.springframework.mail.javamail.JavaMailSender It also provides a callback interface for preparation of JavaMail MIME messages, namely org.springframework.mail.javamail.MimeMessagePreparator

          Spring也支持一個(gè)MailSender的專用于JavaMail特征例如MIME消息子接口,命名為org.springframework.javamail.JavaMailerSener。它也支持一個(gè)為JavaMail MIME信息的準(zhǔn)備回調(diào)接口,命名為org.springframework.mail.JavaMail.MimeMessagePreparator.

          posted on 2007-09-04 17:35 Crying 閱讀(650) 評(píng)論(1)  編輯  收藏 所屬分類: spring

          FeedBack:
          # re: 使用Spring郵件抽象層發(fā)送簡(jiǎn)單郵件(轉(zhuǎn)http://www.aygfsteel.com/shmily432685/archive/2005/12/30/26041.html)
          2007-09-22 13:48 | Crying

          import java.util.*;
          import javax.mail.*;
          import javax.mail.internet.*;
          import javax.activation.*;
          import java.io.*;

          public class SendMail
          {
          static final String MAIL_HOST = "61.177.95.155";
          static final boolean MAIL_NEEDAUTH = true;
          static final String DEFAULT_MAIL_USER = "lioulb@126.com";
          static final String DEFAULT_MAIL_PASSWORD = ".......";
          static final String DEFAULT_FORMAT = "plain"; //純文本
          private MimeMessage mimeMsg; //MIME郵件對(duì)象
          private Multipart mp; //Multipart對(duì)象,郵件內(nèi)容,標(biāo)題,附件等內(nèi)容均添加到其中后再生成MimeMessage對(duì)象
          private Session session; //郵件會(huì)話對(duì)象
          private Properties props; //系統(tǒng)屬性
          private boolean needAuth; //smtp是否需要認(rèn)證
          private String userName; //smtp認(rèn)證用戶名和密碼
          private String password; //smtp認(rèn)證密碼
          private String mailFormat = DEFAULT_FORMAT; //郵件文本格式

          public SendMail(String host,boolean needAuth,String user,String password)
          { //構(gòu)造方法
          if(host==null||host.trim().equals(""))
          {
          host = MAIL_HOST;
          }
          setHost(host);
          createMimeMessage();
          setAuth(needAuth);
          if(user==null)
          {
          user = "";
          }
          if(password==null)
          {
          password = "";
          }
          setUser(user,password);
          setFrom(user);
          }

          public SendMail()
          {
          setHost(MAIL_HOST);
          createMimeMessage();
          setAuth(MAIL_NEEDAUTH);
          setUser(DEFAULT_MAIL_USER,DEFAULT_MAIL_PASSWORD);
          setFrom(DEFAULT_MAIL_USER);
          }

          private void setHost(String hostName)
          { //設(shè)置smtp的主機(jī)地址
          if(props==null)
          {
          props = System.getProperties(); //獲得系統(tǒng)屬性對(duì)象
          }
          props.put("mail.smtp.host",hostName); //設(shè)置SMTP主機(jī)
          }

          private void setAuth(boolean need)
          { //smtp認(rèn)證
          if(props==null)
          {
          props = System.getProperties();
          }
          if(need)
          {
          props.put("mail.smtp.auth","true");
          }
          else
          {
          props.put("mail.smtp.auth","false");
          }
          }

          private void setUser(String userName,String password)
          { //設(shè)置smtp用戶名和密碼
          this.userName = userName;
          this.password = password;
          }

          private boolean createMimeMessage()
          { //生成郵件對(duì)象
          try
          {
          session = Session.getDefaultInstance(props,null); //獲得郵件會(huì)話對(duì)象
          }
          catch(Exception e)
          {
          e.printStackTrace();
          return false;
          }
          try
          {
          mimeMsg = new MimeMessage(session); //創(chuàng)建MIME郵件對(duì)象
          mp = new MimeMultipart();
          return true;
          }
          catch(Exception e)
          {
          e.printStackTrace();
          return false;
          }
          }

          private void setMailFormat(String format)
          { //設(shè)置郵件的正文格式 plain:純文本格式 html:html格式
          if(format==null)
          {
          format = "plain";
          }
          format = format.trim();
          if(format.equals("plain")||format.equals("html"))
          {
          this.mailFormat = "text/"+format;
          }
          else
          {
          this.mailFormat = "text/plain";
          }
          }

          public boolean sendMail(String to,String subject,String body,String format)
          { //發(fā)送不帶附件,不轉(zhuǎn)發(fā)的郵件
          boolean theReturn = true;
          setMailFormat(format);
          // String aLine = Time.getdate()+" "+Time.gettime()+" send: "+this.userName
          //+" "+to+" "+Common.convertToGb(subject);

          String aLine = " send: "+this.userName
          +" "+to+" "+subject;
          if(setSubject(subject)&&setBody(body)&&setTo(to))
          {
          theReturn = sendOut();
          aLine = aLine+" [Success]";
          }
          else
          {
          theReturn = false;
          aLine = aLine+" [Failed]";
          }

          return theReturn;
          }

          public boolean sendMail(String to,String subject,String body)
          {
          return sendMail(to,subject,body,DEFAULT_FORMAT);
          }

          private boolean setSubject(String mailSubject)
          { //設(shè)置郵件主題
          try
          {
          //mailSubject = Common.convertToGb(mailSubject);
          mimeMsg.setSubject(mailSubject);
          return true;
          }
          catch(Exception e)
          {
          e.printStackTrace();
          return false;
          }
          }

          private boolean setBody(String mailBody)
          { //設(shè)置郵件正文
          try
          {
          //mailBody = Common.convertToGb(mailBody);
          BodyPart bp = new MimeBodyPart();
          bp.setContent(mailBody,this.mailFormat+";charset=GB2312"); //"<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+mailBody
          mp.addBodyPart(bp);
          return true;
          }
          catch(Exception e)
          {
          e.printStackTrace();
          return false;
          }
          }

          private boolean setFrom(String from)
          { //設(shè)置發(fā)信人地址
          try
          {
          mimeMsg.setFrom(new InternetAddress(from));
          return true;
          }
          catch(Exception e)
          {
          e.printStackTrace();
          return false;
          }
          }

          private boolean setTo(String to)
          { //設(shè)置收信人地址
          if(to==null)
          {
          return false;
          }
          try
          {
          mimeMsg.addRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
          return true;
          }
          catch(Exception e)
          {
          e.printStackTrace();
          return false;
          }
          }

          private boolean addFileAffix(String filename)
          { //添加附件
          try
          {
          BodyPart bp = new MimeBodyPart();
          FileDataSource fileds = new FileDataSource(filename);
          bp.setDataHandler(new DataHandler(fileds));
          bp.setFileName(fileds.getName());
          mp.addBodyPart(bp);
          return true;
          }
          catch(Exception e)
          {
          e.printStackTrace();
          return false;
          }
          }

          private boolean setCopyTo(String copyto)
          { //設(shè)置轉(zhuǎn)發(fā)人地址
          if(copyto==null)
          {
          return false;
          }
          try
          {
          mimeMsg.addRecipients(Message.RecipientType.CC,
          (Address[])InternetAddress.parse(copyto));
          return true;
          }
          catch(Exception e)
          {
          e.printStackTrace();
          return false;
          }
          }

          public int tryToConnect()
          { //連接郵箱 1:連接成功 0:連接失敗 -1:已經(jīng)連接或系統(tǒng)忙
          int theReturn = 0;
          // String aLine = Time.getdate()+" "+Time.gettime()+" Connect: "+this.userName
          //+" "+this.userName+" "+this.password;

          String aLine = " Connect: "+this.userName
          +" "+this.userName+" "+this.password;
          try
          {
          Session mailSession = Session.getInstance(props,null);
          Transport transport = mailSession.getTransport("smtp");
          transport.connect((String)props.get("mail.smtp.host"),this.userName,
          this.password);
          transport.close();
          theReturn = 1;
          aLine = aLine+" [Success]";
          }
          catch(MessagingException e)
          {
          e.printStackTrace();
          theReturn = 0;
          }
          catch(IllegalStateException e)
          {
          e.printStackTrace();
          theReturn = -1;
          }
          catch(Exception e)
          {
          e.printStackTrace();
          theReturn = 0;
          aLine = aLine+" [Failed]";
          }
          return theReturn;
          }

          private boolean sendOut()
          { //發(fā)送郵件
          try
          {
          mimeMsg.setContent(mp);
          mimeMsg.saveChanges();
          Session mailSession = Session.getInstance(props,null);
          Transport transport = mailSession.getTransport("smtp");
          transport.connect((String)props.get("mail.smtp.host"),this.userName,
          this.password);
          transport.sendMessage(mimeMsg,mimeMsg.getAllRecipients());
          transport.close();
          return true;
          }
          catch(Exception e)
          {
          e.printStackTrace();
          return false;
          }
          }

          public boolean changePwd(String userName,String newPwd)
          { //修改郵箱密碼
          boolean theReturn = false;
          try
          {
          String commond = "passwd "+userName;
          Process process = Runtime.getRuntime().exec(commond);
          BufferedReader br = new BufferedReader(new InputStreamReader(process.
          getInputStream()));
          PrintStream ps = new PrintStream(process.getOutputStream());
          BufferedReader br1 = new BufferedReader(new InputStreamReader(process.
          getErrorStream()));
          char ac[] = new char[1024];
          br1.read(ac);
          ps.println(newPwd);
          ps.flush();
          br1.read(ac);
          ps.println(newPwd);
          ps.flush();
          br1.read(ac);
          if(process.waitFor()==0)
          {
          theReturn = true;
          }
          }
          catch(Exception e)
          {
          e.printStackTrace();
          //e.printStackTrace(System.out);
          System.out.println(e.toString());
          theReturn = false;
          }
          return theReturn;
          }

          public boolean addUser(String userName)
          { //添加郵件用戶 (密碼默認(rèn)為空)
          boolean theReturn = false;
          try
          {
          String commond = "/usr/sbin/useradd "+userName+
          " -g mail -d /dev/null -s /bin/false";
          Process process = Runtime.getRuntime().exec(commond);
          BufferedReader br = new BufferedReader(new InputStreamReader(process.
          getInputStream()));
          PrintStream ps = new PrintStream(process.getOutputStream());
          BufferedReader br1 = new BufferedReader(new InputStreamReader(process.
          getErrorStream()));
          char ac[] = new char[1024];
          br1.read(ac);
          if(process.waitFor()==0)
          {
          theReturn = true;
          }
          }
          catch(Exception e)
          {
          e.printStackTrace(System.out);
          theReturn = false;
          }
          return theReturn;
          }

          public boolean addUser(String userName,String pwd)
          { //添加郵件用戶
          boolean theReturn = addUser(userName);
          if(theReturn)
          {
          theReturn = changePwd(userName,pwd);
          if(!theReturn)
          { //修改密碼失敗
          deleUser(userName);
          }
          }
          return theReturn;
          }

          public boolean deleUser(String userName)
          { //刪除郵件用戶
          boolean theReturn = false;
          try
          {
          String commond = "/usr/sbin/userdel "+userName;
          Process process = Runtime.getRuntime().exec(commond);
          BufferedReader br = new BufferedReader(new InputStreamReader(process.
          getInputStream()));
          PrintStream ps = new PrintStream(process.getOutputStream());
          BufferedReader br1 = new BufferedReader(new InputStreamReader(process.
          getErrorStream()));
          char ac[] = new char[1024];
          br1.read(ac);
          if(process.waitFor()==0)
          {
          theReturn = true;
          }
          }
          catch(Exception exception)
          {
          exception.printStackTrace(System.out);
          theReturn = false;
          }
          return theReturn;
          }

          public static void main(String args[]){
          SendMail myMail=new SendMail();
          System.out.println(myMail.sendMail("oxservice@126.com","this is test","my \n test"));
          }
          }
            回復(fù)  更多評(píng)論
            
          主站蜘蛛池模板: 渝北区| 东光县| 壤塘县| 牡丹江市| 府谷县| 广河县| 富宁县| 昌图县| 恩施市| 怀柔区| 武义县| 修武县| 枝江市| 昌乐县| 肇庆市| 泌阳县| 宁乡县| 铜陵市| 杨浦区| 汉沽区| 红河县| 南投市| 宁乡县| 英超| 井研县| 崇明县| 年辖:市辖区| 南开区| 罗田县| 鄯善县| 常山县| 基隆市| 拜泉县| 五指山市| 伊通| 房山区| 肥西县| 福建省| 五河县| 双辽市| 娱乐|