丄諦啲仇魜ヤ
如 果 敌 人 让 你 生 气 , 那 说 明 你 没 有 胜 他 的 把 握!
posts - 6,comments - 56,trackbacks - 1
Spring提供了一个发送电子邮件的高级抽象层,它向用户屏蔽了底层邮件系统的一些细节,同时负责低层次的代表客户端的资源处理。Spring邮件抽象层的主要包为org.springframework.mail。它包括了发送电子邮件的主要接口MailSender和 封装了简单邮件的属性如from, to,cc, subject, text的值对象叫做SimpleMailMessage。
1、我们定义一个发送邮件的接口:OrderManager.java
1 public interface OrderManager extends BaseManager{
2 /**
3 *email,要发送的邮件地址;
4 *Code:激活码
5 */
6      public void placeOrder(String email);
7 }

2、我们需要对该接口进行实现的方法: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                 /**转换编码为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配置发送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>标题</value>
30         </property>
31         <property name="text">
32             <value>内容</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页面以及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 }

到此所有的开发以结束。

Sring邮件抽象层的主要包是:org.springframework.mail 包。它包含叫MailSender为发送邮件的核心接口和包含简单邮件属性例如from,to,cc,subject,text叫SimpleMailMessage的值对象. 这个包也包含一个检查异常的层次,它支持一个更高级别的抽象超过低级别的邮件系统异常伴随根异常存在MailException. 请参考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也支持一个MailSender的专用于JavaMail特征例如MIME消息子接口,命名为org.springframework.javamail.JavaMailerSener。它也支持一个为JavaMail MIME信息的准备回调接口,命名为org.springframework.mail.JavaMail.MimeMessagePreparator.

posted on 2007-09-04 17:35 Crying 阅读(641) 评论(1)  编辑  收藏 所属分类: spring

FeedBack:
# re: 使用Spring邮件抽象层发送简单邮件(转http://www.blogjava.net/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邮件对象
private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
private Session session; //邮件会话对象
private Properties props; //系统属性
private boolean needAuth; //smtp是否需要认证
private String userName; //smtp认证用户名和密码
private String password; //smtp认证密码
private String mailFormat = DEFAULT_FORMAT; //邮件文本格式

public SendMail(String host,boolean needAuth,String user,String password)
{ //构造方法
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)
{ //设置smtp的主机地址
if(props==null)
{
props = System.getProperties(); //获得系统属性对象
}
props.put("mail.smtp.host",hostName); //设置SMTP主机
}

private void setAuth(boolean need)
{ //smtp认证
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)
{ //设置smtp用户名和密码
this.userName = userName;
this.password = password;
}

private boolean createMimeMessage()
{ //生成邮件对象
try
{
session = Session.getDefaultInstance(props,null); //获得邮件会话对象
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
try
{
mimeMsg = new MimeMessage(session); //创建MIME邮件对象
mp = new MimeMultipart();
return true;
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}

private void setMailFormat(String format)
{ //设置邮件的正文格式 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)
{ //发送不带附件,不转发的邮件
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)
{ //设置邮件主题
try
{
//mailSubject = Common.convertToGb(mailSubject);
mimeMsg.setSubject(mailSubject);
return true;
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}

private boolean setBody(String mailBody)
{ //设置邮件正文
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)
{ //设置发信人地址
try
{
mimeMsg.setFrom(new InternetAddress(from));
return true;
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}

private boolean setTo(String to)
{ //设置收信人地址
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)
{ //设置转发人地址
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:已经连接或系统忙
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()
{ //发送邮件
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)
{ //添加邮件用户 (密码默认为空)
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"));
}
}
  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: