`

用 Apache James 搭建邮件服务器来收发邮件实践(一)

阅读更多

       Apache James 简称 James, 是 Java Apache Mail Enterprise Server的缩写。James 是100%基于Java的电子邮件服务器。它是一种独立的邮件服务器,并提供了一个完整的电子邮件解决方案,用来收、发电子邮件。

 

       本文不赘述James服务器的参数细节,这个以后有机会再详细讨论,这里先从服务器搭建开始,用搭建的服务器收、发电子邮件来熟悉一下Apache James。本人也是新手,希望能得到各位高手的指点,使大家能悟到进阶的方向。

 

       开始之前,先声明一下本文操作的系统环境:

       1. JDK 6u10b

       2. JMail API v1.4.2

       3. JAF API v1.1(JavaBean Activation Framework)

       4. Apache James 2.3.1

       5. Eclipse 3.4 for J2EE Developers

       6. Windows 2000 Server sp4

 

    

       

       1。请下载安装JDK,并设置好其环境变量:JAVA_HOME=…… 、PATH=…… 、CLASSPATH=…… Eclipse 3.4 是目前的最新版本,可以从http://www.eclipse.org/下载。

      

       2。请下载JMail API、JAF API,可以在www.java.sun.com找到他们,找不到也不要紧,本文附件示例代码免费提供一份(^_^)。

 

       3。Apache James 的官方网站为:http://james.apache.org/,当前 Server 的最新版为 2.3.1版. 安装非常简单,下载后得到james-binary-2.3.1.zip 文件,解压后即可。这里假设解压到D盘(D:\james-2.3.1),目录结构如下:

      

       D:\james-2.3.1

               |--- apps

               |--- bin

               |

       …………

 

       4。启动 James 服务器

       双击或在命令行下执行D:\james-2.3.1\bin 目录下的 run.bat文件,即可启动 James 服务器。

 

       启动后能在控制台看到如下信息,说明启动成功:

Using PHOENIX_HOME: D:\james-2.3.1 
Using PHOENIX_TMPDIR: D:\james-2.3.1\temp 
Using JAVA_HOME: D:\Java\jdk1.6.0_10 

Phoenix 4.2 

James Mail Server 2.3.1 
Remote Manager Service started plain:4555 
POP3 Service started plain:110 
SMTP Service started plain:25 
NNTP Service started plain:119 
FetchMail Disabled

   

      

       要关闭 James 服务,请使用 Ctrl + C

 

       说明:启动前请确保您的JDK环境变量如JAVA_HOME等已经设置好;James 启动时,其SMTP 服务默认在 25 端口启动,POP3 服务默认在 110 端口启动, NNTP 服务默认在 119 端口启动, 请确保这些端口未被占用。比如本系统下就已经安装了Microsoft的 SMTP 服务,造成 James无法启动,解决方法为:开始--->设置--->控制面板--->管理工具--->服务,打开后找到“Simple Mail Transport Protocol(SMTP)”服务项,关闭即可。

 

     

       5。配置服务

       服务器启动后会在本机配置一个默认的服务,这可以用来在本机上本服务器范围内收发邮件,但是邮件发不到163等外网邮箱。我们这里关注的重点就是配置一个能发到外网如163这样的邮箱的邮件,这样才有价值。不过由于本人是在本机上测试,一时不能获取公司的域名参数,无法测试接收外网邮箱(如163)的邮件,见晾,不过做法都是一样的,至少我们可以向外网邮箱发送邮件,局域网内可以收、发邮件。

      

        打开D:\james-2.3.1\apps\james\SAR-INF 下的 config.xml 文件,初次启动James之前,不会有这个文件,只有当James服务启动一次之后才自动构件该文件。

      

        找到

…… 
<postmaster>Postmaster@localhost</postmaster> 
…… 
<servernames autodetect="true" autodetectIP="true"> 
	<servername>localhost</servername> 
</servernames> 
…… 

  

  

        把localhost该成你自己想要的邮箱域名, 把自动探测IP属性设置为“false”这里假设改成 zhaipuhong.com 如果开了一个帐号 zph ,那么他的邮件地址就是 zph@zhaipuhong.com (^_^)修改结果如下:

 

…… 
<postmaster>Postmaster@zhaipuhong.com</postmaster> 
…… 
<servernames autodetect="false" autodetectIP="false"> 
	<servername>zhaipuhong.com</servername> 
</servernames> 
……

   

        找到

<mailet match="RemoteAddrNotInNetwork=127.0.0.1" class="ToProcessor"> 
	<processor> relay-denied </processor> 
	<notice>550 - Requested action not taken: relaying denied</notice> 
</mailet>

   

        将其注释,结果如下:

<!--mailet match="RemoteAddrNotInNetwork=127.0.0.1" class="ToProcessor"> 
	<processor> relay-denied </processor> 
	<notice>550 - Requested action not taken: relaying denied</notice> 
</mailet-->

    

         找到下面元素,去掉其注释

<authRequired>true</authRequired>

  

 

         这样邮箱访问需要帐号验证,你不希望别人用你的帐号收发消息吧……^_^

        

         如此,James服务配置已经完成。

 

 

        6。创建邮件帐号

        创建邮件帐号后,就可以用来收发邮件了。James的账号管理是通过基于Telnet客户机的远程管理器,这点颇为不爽,尤其是我的操作系统下的命令行控制台是不显示telnet命令输入字符的,经常出错。

 

        现在进入命令行控制台,在telnet localhsot 4555 进入James管理器,操作如下:

C:\Documents and Settings\db2admin>telnet localhost 4555 

  

 

        将进入

JAMES Remote Administration Tool 2.3.1 Please enter your login and password Login id:

   

 

        默认的登陆id 为root 密码也为 root ,登陆成功后结果如下:

JAMES Remote Administration Tool 2.3.1 
Please enter your login and password 
Login id: 
Password: 
Welcome root. HELP for a list of commands  

 

       创建新用户的命令是:adduser username password

    这里创建了两个账户来作为演示使用: zhaipuhong/zhangpuhong ;      zph/zph

 

      说明:你可以输入help来获取命令帮助

help display this help 显示帮助信息 
listusers display existing accounts 显示现有账户 
countusers display the number of existing accounts 显示现有账户数量 
adduser [username] [password] add a new user 添加一个新用户 
verify [username] verify if specified user exist 核实指定用户是否存在 
deluser [username] delete existing user 删除存在的用户 
setpassword [username] [password] sets a user's password 设置用户密码 
setalias [user] [alias] locally forwards all email for 'user' to 'alias' 设置邮箱别名 
showalias [username] shows a user's current email alias 显示别名 
unsetalias [user] unsets an alias for 'user' 删除用户别名 
setforwarding [username] [emailaddress] forwards a user's email to another email address 转发用户的电子邮件地址到另一个电子邮件地址 
showforwarding [username] shows a user's current email forwarding 显示用户的当前邮件转发 
unsetforwarding [username] emoves a forward 删除转发 
user [repositoryname] change to another user repository 改变另一个用户库 
shutdown kills the current JVM (convenient when James is run as a daemon)关闭当前的服务 
quit close connection 关闭连接

  

 

 

 

      账号创建成功后,使用quit退出管理器。现在我们可以开始部署我们的JMail应用了。

 

 

      7。用James收发邮件

      现在我们来写两个简单的程序来体验一下如何使用James收发邮件。请注意,示例程序是通用的。关于如何用JMail API收发邮件,这里不详细介绍,如果还没有接触过请参考一下我之前的文章:

      http://zhaipuhong.iteye.com/admin/blogs/213005

     

      关于接受邮件部分,我们在代码中通过注释来描述。另外我们来回忆一下上述步骤配置James服务器的参数:

      1。smtp 服务器:192.168.1.98或者localhost     192.168.1.98是我的局域网IP,由于我James服务就装在我的机器上,所以我可以用localhost

      2。两个邮件帐号:zhaipuhong/zhaipuhong   对应邮箱地址: zhaipuhong@zhaipuhong.com

                                zph/zph                            对应邮箱地址: zph@zhaipuhong.com

      注意:邮箱域名我们配置的是zhaipuhong.com

 

      示例程序:

 

package com.zhaipuhong.j2ee.jmail;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class HelloJMail {
	
	//发送邮件
	public static void sendMail() {
		//String host = "192.168.1.98"; // 指定的smtp服务器,本机的局域网IP
		String host = "localhost"; // 本机smtp服务器
		//String host = "smtp.163.com"; // 163的smtp服务器
		String from = "zhaipuhong@zhaipuhong.com"; // 邮件发送人的邮件地址
		String to = "zph@zhaipuhong.com"; // 邮件接收人的邮件地址
		final String username = "zhaipuhong";  //发件人的邮件帐户
		final String password = "zhaipuhong";   //发件人的邮件密码

		// 创建Properties 对象
		Properties props = System.getProperties();

		// 添加smtp服务器属性
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.auth", "true");

		// 创建邮件会话
		Session session = Session.getDefaultInstance(props, new Authenticator(){
			@Override
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
			
		});

		try {
			// 定义邮件信息
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					to));
			//message.setSubject(transferChinese("我有自己的邮件服务器了"));
			message.setSubject("I hava my own mail server");
			message.setText("From now, you have your own mail server, congratulation!");

			// 发送消息
			session.getTransport("smtp").send(message);  
			//Transport.send(message); //也可以这样创建Transport对象发送
			System.out.println("SendMail Process Over!");

		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	//接受邮件
	public static void getMail(){
		String host = "localhost";
	    final String username = "zph";
		final String password = "zph";

		// 创建Properties 对象
	    Properties props = new Properties();

		// 创建邮件会话
		Session session = Session.getDefaultInstance(props, new Authenticator(){
			@Override
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
			
		});

	    
		try {
			// 获取邮箱的pop3存储
			Store store = session.getStore("pop3");
			store.connect(host, username, password);

	        // 获取inbox文件
		    Folder folder = store.getFolder("INBOX");
		    folder.open(Folder.READ_ONLY);  //打开,打开后才能读取邮件信息

		    // 获取邮件消息
		    Message message[] = folder.getMessages();

		    for (int i=0, n=message.length; i<n; i++) {
		    	System.out.println(i + ": " + message[i].getFrom()[0]
		    	                               + "\t" + message[i].getSubject());
		    	try {
					message[i].writeTo(System.out);
				} catch (IOException e) {
					e.printStackTrace();
				}

		    }

		    // 关闭资源
		    folder.close(false);
		    store.close();
		    
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
		System.out.println("GetMail Process Over!");

	}
	
	//邮件主题中文字符转换
	public static String transferChinese(String strText){
		try{
			strText = MimeUtility.encodeText(new String(strText.getBytes(), "GB2312"), "GB2312", "B");
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return strText;
	}

	public static void main(String[] args) {
		HelloJMail.sendMail();
		//HelloJMail.getMail();
	}

}

  

 

 

 

      说明: 执行测试时,先执行发送,在main方法中注释掉邮件接受方法调用,等待片刻,再注释掉邮件发送方法调用,执行邮件接受方法调用。因为就算163这样优秀的企业级邮箱也不可能瞬间就能收到发送的邮件。

      在邮件发送方法中:sendMail(), 可以尝试一下又本邮件服务器向163邮箱发送邮件,如果想通过163邮件服务器想本地发送邮件,你需要配置DSN。

  

       以下为本机接收James邮件服务器提供服务的邮件结果:

 

0: zhaipuhong@zhaipuhong.com	I hava my own mail server
Return-Path: <zhaipuhong@zhaipuhong.com>
Delivered-To: zph@zhaipuhong.com
Received: from 127.0.0.1 ([127.0.0.1])
          by ZPH (JAMES SMTP Server 2.3.1) with SMTP ID 693
          for <zph@zhaipuhong.com>;
          Wed, 9 Jul 2008 19:58:38 +0800 (CST)
Date: Wed, 9 Jul 2008 19:58:38 +0800 (CST)
From: zhaipuhong@zhaipuhong.com
To: zph@zhaipuhong.com
Message-ID: <11627000.01215604718796.JavaMail.db2admin@ZPH>
Subject: I hava my own mail server
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

From now, you have your own mail server, congratulation!

  

 

 

       从上面的结果可以看出,该邮件是由zhaipuhong@zhaipuhong.com 发给 zph@zhaipuhong.com 的。

     

       多发几封电子邮件,就会发现,James 的邮件接收是一个栈结构,最近收到的邮件编号为0,依次类推……

  

 

 

  • practice.rar (370.3 KB)
  • 描述: 项目的示例代码
  • 下载次数: 2206
  • config.rar (14.7 KB)
  • 描述: James 的配置文件,可以直接替换使用
  • 下载次数: 1332
分享到:
评论
41 楼 yl23250 2013-07-24  
C:\Documents and Settings\db2admin>telnet localhost 4555 


这行什么意思啊。。。我的win7跟你不一样啊

C:\Users\Administrator>
我的是这样的。大神。。。怎么弄?
40 楼 jinxueliu 2009-06-19  
我想通过web页面进行注册,并将用户名,密码,邮件等内容存储在数据库中
但我不知道该如何在james中配置数据库的相关参数
网络上都是mysql的例子,现在我需要的是sqlserver的配置(oracle的也可以)
谢谢楼主
39 楼 taupo 2009-06-11  
zhaipuhong 写道
myy 能不能详细的讲一讲这个基本机制呢。

  套接字。。。。。。。嘿嘿
38 楼 lovejzp 2009-05-25  
请问 楼主 ,关于 JavaMail的 Monitor,James能配置吗?官方注明是试验版的,能用吗?还有就是pop3Store 好像没有addMessageCountListener方法,那假如想实现 监听新邮件的功能 ,有没有好的方法?
37 楼 tcrct 2009-05-14  
原来已经可以发的了,不过就只能发到163的邮箱中,其它的一律不行。这又是为什么呢?
36 楼 tcrct 2009-05-14  
楼主,我想问一下,我按你的方法做了,不过,我的不知为什么没生效!james的后台也就是DOS窗口那里没有其实信息的。这是为什么呢?
35 楼 zhaipuhong 2008-09-25  
代理服务器联路邮的情况没有尝试过怎么配置,不过我想Apache的邮件服务器不可能因为是代理上网就不能用了吧,我觉得没有影响。
34 楼 mars李 2008-09-23  
我电脑目前在公司使用代理服务器联上路邮的.
这种情况在我机器上部署james,是否能用正常用james收发邮件.
33 楼 zhaipuhong 2008-09-13  
hszhl“程序可以运行,但james没有提示你讲的信息”

不知道你哪里遇到了问题,可以说的具体些吗?
32 楼 hszhl 2008-09-10  
程序可以运行,但james没有提示你讲的信息
31 楼 zhaipuhong 2008-09-02  
当然是能发了,只是以后安全和反垃圾方面会做的更好!
30 楼 haiter 2008-09-02  
真搞不懂,以后邮件服务器之间可能不能相互发邮件
29 楼 zhaipuhong 2008-09-02  
// 添加smtp服务器属性
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");


这两行我都有啊,老兄!
28 楼 haiter 2008-09-02  
新浪总是报如下错误:
Hi. This is the James mail server at good.
I'm afraid I wasn't able to deliver your message to the following addresses.
This is a permanent error; I've given up. Sorry it didn't work out.  Below
I include the list of recipients and the reason why I was unable to deliver
your message.

Failed recipient(s):
dengjidou@sina.com

Error message:
550 #5.7.1 Your access to submit messages to this e-mail system has been rejected.
27 楼 haiter 2008-09-02  
这么快看到了你的回复!
报"530 5.7.1 Authentication Required" ,是因为
没有 props.put("mail.smtp.auth", "true");
现在sina就是收不到,其他邮件可以收到,
我的www.51newlife.com是真实注册的域名
我打算用版本3.0试试看
26 楼 zhaipuhong 2008-09-02  
毕竟你只是一个未注册的域名,当初都是测试通过了的,昨天我给自己新浪发的也没收到。不知道新浪的安全机制或者反垃圾邮件这么强。有待进一步证实!
25 楼 haiter 2008-09-02  
我修改了配置文件如下,请大家一起来讨论一下
<helloName autodetect="true">51newlife.com</helloName>
<defaultDomain>51newlife.com</defaultDomain>

<servernames autodetect="false" autodetectIP="true">
         <servername>51newlife.com</servername>
</servernames>
<!--<mailet match="RemoteAddrNotInNetwork=127.0.0.1" class="ToProcessor">
            <processor> relay-denied </processor>
            <notice>550 - Requested action not taken: relaying denied</notice>
         </mailet>
          -->

<authRequired>true</authRequired>
24 楼 haiter 2008-09-02  
zhai puhong :
我测试了一下可以向dengjidou@163.com发,可以成功收到,
但向sina.com发收不到,报"530 5.7.1 Authentication Required"
你发的邮件我没有收到
23 楼 zhaipuhong 2008-09-01  
haiter,网易和新浪的邮箱都是可以发的,新浪的邮箱可能没有网易的邮箱那么快收到,这些我都是做个测试的。我特地又做了一遍测试。另外,我向你的dengjidou@sina.com 邮箱发了一封邮件,希望你能收到^_^

另外根据报错,是sina邮箱拒绝了你的邮件。你再研究一下是哪里出了问题。希望你有了结果能来这跟大家讲讲你的发现。谢谢!
22 楼 haiter 2008-09-01  
按照你的配置方式,我的返回如下错误,不知如何解决
Hi. This is the James mail server at good.
I'm afraid I wasn't able to deliver your message to the following addresses.
This is a permanent error; I've given up. Sorry it didn't work out.  Below
I include the list of recipients and the reason why I was unable to deliver
your message.

Failed recipient(s):
dengjidou@sina.com

Error message:
550 #5.7.1 Your access to submit messages to this e-mail system has been rejected.

相关推荐

Global site tag (gtag.js) - Google Analytics