---
title: "JMS_发送邮件"
author: "j040404"
date: "2008-06-06T00:06:00Z"
tags: []
slug: "jms"
draft: false
lastmod: "2008-06-06T00:06:00Z"
id: 260089
url: "https://j040404.iteye.com/blog/260089"
---

看这个例子之前最好先看下“我的资源”里的《EJB3.0开发Message Driven Bean》教怎样开发MDB，还配有图片，很好的实例

下面看怎样开发JMS发送邮件

首先需要配置个mail文件

路径在：%JBOSS\_HOME%\\server\\all\\deploy中有个mail-service.xml

打开它，大致修改成：

 &lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;!DOCTYPE server&gt;  
&lt;!-- $Id: mail-service.xml,v 1.5.6.1 2005/06/01 06:20:43 starksm Exp $ --&gt;

&lt;server&gt;

  &lt;!-- ==================================================================== --&gt;  
  &lt;!-- Mail Connection Factory                                              --&gt;  
  &lt;!-- ==================================================================== --&gt;

  &lt;mbean code="org.jboss.mail.MailService"  
         name="jboss:service=Mail"&gt;  
    &lt;attribute name="JNDIName"&gt;java:/Mail&lt;/attribute&gt;  
    &lt;attribute name="User"&gt;邮箱的用户名&lt;/attribute&gt;  
    &lt;attribute name="Password"&gt;邮箱的密码&lt;/attribute&gt;  
    &lt;attribute name="Configuration"&gt;  
       &lt;!-- Test --&gt;  
       &lt;configuration&gt;  
          &lt;!-- Change to your mail server prototocol --&gt;  
          &lt;property name="mail.store.protocol" value="pop3"/&gt;  
          &lt;property name="mail.transport.protocol" value="smtp"/&gt;

          &lt;!-- Change to the user who will receive mail  --&gt;  
          &lt;property name="mail.user" value="nobody"/&gt;

          &lt;!-- Change to the mail server  --&gt;  
          &lt;property name="mail.pop3.host" value="pop3.163.com"/&gt;

          &lt;!-- Change to the SMTP gateway server --&gt;  
          &lt;property name="mail.smtp.host" value="smtp.163.com"/&gt;  
     
    &lt;property name="mail.smtp.auth" value="true"/&gt;

          &lt;!-- Change to the address mail will be from  --&gt;  
          &lt;property name="mail.from" value="用户名[@邮箱（例如：163）.com"/](mailto:lljangels@163.com%22/)&gt;

          &lt;!-- Enable debugging output from the javamail classes --&gt;  
          &lt;property name="mail.debug" value="false"/&gt;  
       &lt;/configuration&gt;  
       &lt;depends&gt;jboss:service=Naming&lt;/depends&gt;  
    &lt;/attribute&gt;  
  &lt;/mbean&gt;

&lt;/server&gt;

建立一个ejb3.0的项目

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/1.jpg)

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/2.jpg)

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/3.jpg)

图上的myjboss是我先前建的jboss服务器。

下面是如果没有jboss server建立新的服务器的过程

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/4.jpg)

选择jboss as4.0

 

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/5.jpg)

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/6.jpg)

点击完成以后又回到这个界面，因为之前有服务器了，我就没有新建，然后点完成

 

```
package examples.Message;

import javax.ejb.*;
import javax.naming.*;
import javax.jms.*;
import java.util.*;
import java.text.*;
import javax.mail.*;
import javax.mail.internet.*;

/**
 * MessageBean class must implement two interfaces MessageDrivenBean and
 * MessageListener
 */
@SuppressWarnings( { "serial", "unused" })
@MessageDriven(activationConfig =

{

@ActivationConfigProperty(propertyName = "destinationType",

propertyValue = "javax.jms.Queue"),

@ActivationConfigProperty(propertyName = "destination",

propertyValue = "queue/testQueue")

})
public class MessageBean implements MessageListener {

	private transient MessageDrivenContext context = null;

	/**
	 * a no-argument constructor
	 */
	public MessageBean() {
	}

	/**
	 * called by container during object creation
	 */

	/**
	 * The onMessage Method receives the Message parameter, type casts it to the
	 * appropriate message type and prints the contents of the message. A mail
	 * note is then sent to the message sender
	 */
	public void onMessage(javax.jms.Message msg) {
		try {
			if (msg instanceof MapMessage) {
				MapMessage map = (MapMessage) msg;
				System.out.println("Order   received:   ");
				System.out.println("Order   ID:   " + map.getString("OrderID")
						+ "   Item   ID:   " +

						map.getInt("ItemID") + "   Quanity:   "
						+ map.getInt("Quantity") + "   Unit   Price:   " +

						map.getDouble("UnitPrice"));
				sendNote(map.getString("emailID"));
			} else {
				System.out.println("wrong   message   type");
			}
		} catch (Throwable te) {
			te.printStackTrace();
		}
	}

	/**
	 * Sends an e-mail notification to the recipient e-mail ID specified in the
	 * input parameter
	 */
	private void sendNote(String recipient) {
		try {
			// Initialize JNDI context
			Context initial = new InitialContext();

			// look up the mail server session
			
			javax.mail.Session session = (javax.mail.Session)

			initial.lookup("java:/Mail");
			

			// Create a new mail object
			javax.mail.Message msg = new MimeMessage(session);

			// set various mail properties
			msg.setFrom();

			msg.setRecipients(javax.mail.Message.RecipientType.TO,
					InternetAddress.parse(recipient,

					false));

			msg.setSubject("您有一封信邮件");

			DateFormat dateFormatter = DateFormat.getDateTimeInstance(
					DateFormat.LONG,

					DateFormat.SHORT);

			Date timeStamp = new Date();

			String messageText = "恭喜您，邮件发送成功 "
					+ dateFormatter.format(timeStamp) + ".";

			msg.setText(messageText);

			msg.setSentDate(timeStamp);

			// send the mail message
			Transport.send(msg);

		} catch (Exception e) {
			throw new EJBException(e.getMessage());
		}
	}

}
```

根据上面代码的包名和类名，把这个类建好。然后会报错，解决过程如下图

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/7.jpg)

 

 

 ![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/8.jpg)

点击add external jars..导入之前下载的mail.jar

下载地址是：

[http://cds-esd.sun.com/ESD36/JSCDL/javamail/1.4.1/javamail-1\_4\_1.zip?AuthParam=1212507419\_fada7a5c54305290323a361afbe9149d&TicketId=B%2Fw2lR6BSl5JSBRCOV5flgDh&GroupName=CDS&FilePath=/ESD36/JSCDL/javamail/1.4.1/javamail-1\_4\_1.zip&File=javamail-1\_4\_1.zip](http://cds-esd.sun.com/ESD36/JSCDL/javamail/1.4.1/javamail-1_4_1.zip?AuthParam=1212507419_fada7a5c54305290323a361afbe9149d&amp%3BTicketId=B%2Fw2lR6BSl5JSBRCOV5flgDh&amp%3BGroupName=CDS&amp%3BFilePath=%2FESD36%2FJSCDL%2Fjavamail%2F1.4.1%2Fjavamail-1_4_1.zip&amp%3BFile=javamail-1_4_1.zip)

然后把该项目打包成jar文件，放到%JBOSS\_HOME%\\server\\all\\deploy下过程如下

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/9.jpg)

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/10.jpg)

然后测试，也相当于客户端

建立动态web项目

 ![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/11.jpg)

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/12.jpg)

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/13.jpg)

在doGet中添加以下代码：

```
		Context jndiContext = null;
		QueueConnectionFactory queueConnectionFactory = null;
		QueueConnection queueConnection = null;
		QueueSession queueSession = null;
		Queue queue = null;
		QueueSender queueSender = null;
		MapMessage message = null;
		@SuppressWarnings("unused")
		final int NUM_MSGS;

		/*
		 * if ((args.length < 1)) { System.out.println("Usage: java
		 * MessageClient " + ""); System.exit(1); }
		 */

		// Obtain JNDI context and
		// Look up connection factory and queue.
		try {
			jndiContext = new InitialContext();

			Object tmp = jndiContext.lookup("ConnectionFactory");

			queueConnectionFactory = (QueueConnectionFactory) tmp;

			// queueConnection = queueConnectionFactory.createQueueConnection();
			/*
			 * queueConnectionFactory = (QueueConnectionFactory) jndiContext
			 * .lookup("java:comp/env/QueueConnectionFactory");
			 * 
			 * queue = (Queue) jndiContext.lookup(args[0]);
			 */
			queue = (Queue) jndiContext.lookup("queue/testQueue");

		} catch (NamingException e) {

			System.out.println("JNDI   lookup   failed:   " + e.toString());
			System.exit(1);
		}

		/*
		 * Create session from connection; false means session is not
		 * transacted. Create sender and map message. Send messages, varying
		 * text slightly. Send end-of-messages message. Finally, close
		 * connection.
		 */
		try {
			// Create connection.
			queueConnection = queueConnectionFactory.createQueueConnection();

			// Create session from connection
			queueSession = queueConnection.createQueueSession(false,

			QueueSession.AUTO_ACKNOWLEDGE);

			queueConnection.start();

			// Create Sender
			queueSender = queueSession.createSender(queue);

			// Create Map Message
			message = queueSession.createMapMessage();

			// Define several Name/Value pairs
			message.setString("OrderID", "1");

			message.setInt("ItemID", 5);

			message.setInt("Quantity", 50);

			message.setDouble("UnitPrice", 5.00);

			message.setString("emailID", "254164472@qq.com");// 注意，邮箱添自己的

			// Send message
			queueSender.send(message);

		} catch (JMSException e) {
			System.out.println("Exception   occurred:   " + e.toString());
		} finally {
			if (queueConnection != null) {
				try {
					queueConnection.close();
				} catch (JMSException e) {
				}
			}
		}
	
```

上面代码中，有个邮箱地址，那添自己的邮箱。否则邮件就会发送到254164472.qq.com里了

粘贴完如果报错，可以把鼠标放到错误的那行按住Ctrl+1然后选add library...

 

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/14.jpg)

 

然后部署到服务器上，进行测试

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/15.jpg)

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/16.jpg)

点击完成就可以了，如果没有jboss可以选择（单选按钮）下面那个新建一个服务器

然后点击完成。等jboss启动完

在IE中地址栏输入：[http://localhost:8080/JMS\_Client/testJMS](http://localhost:8080/JMS_Client/testJMS)

如果把上面servlet 中的邮箱地址写成自己的，那么此时就会收到一封邮件。