ITeye博客

JMS_发送邮件

j040404 · 2008-06-06 00:06 · Markdown

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

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

首先需要配置个mail文件

路径在:%JBOSS_HOME%\server\all\deploy中有个mail-service.xml

打开它,大致修改成:

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

<server>

  <!-- ==================================================================== -->
  <!-- Mail Connection Factory                                              -->
  <!-- ==================================================================== -->

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

          <!-- Change to the user who will receive mail  -->
          <property name="mail.user" value="nobody"/>

          <!-- Change to the mail server  -->
          <property name="mail.pop3.host" value="pop3.163.com"/>

          <!-- Change to the SMTP gateway server -->
          <property name="mail.smtp.host" value="smtp.163.com"/>
   
    <property name="mail.smtp.auth" value="true"/>

          <!-- Change to the address mail will be from  -->
          <property name="mail.from" value="用户名@邮箱(例如:163).com"/>

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

</server>

建立一个ejb3.0的项目

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

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

选择jboss as4.0

 

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

 

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());
		}
	}

}

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

 

 

 

点击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

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

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

建立动态web项目

 

在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...

 

 

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

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

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

在IE中地址栏输入:http://localhost:8080/JMS_Client/testJMS

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。