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 服務器。



啓動後能在控制檯看到如下信息,說明啓動成功:

Java代碼
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

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服務啓動一次之後才自動構件該文件。



找到

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

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



把localhost該成你自己想要的郵箱域名, 把自動探測IP屬性設置爲“false”這裏假設改成 zhaipuhong.com 如果開了一個帳號 zph ,那麼他的郵件地址就是 [email protected] (^_^)修改結果如下:



Xml代碼
……
<postmaster>[email protected]</postmaster>
……
<servernames autodetect="false" autodetectIP="false">
<servername>zhaipuhong.com</servername>
</servernames>
……

……
<postmaster>[email protected]</postmaster>
……
<servernames autodetect="false" autodetectIP="false">
<servername>zhaipuhong.com</servername>
</servernames>
……

找到

Xml代碼
<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>

將其註釋,結果如下:

Xml代碼
<!--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-->

找到下面元素,去掉其註釋

Xml代碼
<authRequired>true</authRequired>

<authRequired>true</authRequired>



這樣郵箱訪問需要帳號驗證,你不希望別人用你的帳號收發消息吧……^_^



如此,James服務配置已經完成。





6。創建郵件帳號

創建郵件帳號後,就可以用來收發郵件了。James的賬號管理是通過基於Telnet客戶機的遠程管理器,這點頗爲不爽,尤其是我的操作系統下的命令行控制檯是不顯示telnet命令輸入字符的,經常出錯。



現在進入命令行控制檯,在telnet localhsot 4555 進入James管理器,操作如下:

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

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



將進入

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

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



默認的登陸id 爲root 密碼也爲 root ,登陸成功後結果如下:

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

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來獲取命令幫助


C代碼
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 關閉連接

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 對應郵箱地址: [email protected]
zph/zph 對應郵箱地址: [email protected]
注意:郵箱域名我們配置的是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 = "[email protected]"; // 郵件發送人的郵件地址
String to = "[email protected]"; // 郵件接收人的郵件地址
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: [email protected]    I hava my own mail server   Return-Path: <[email protected]>   Delivered-To: [email protected]   Received: from 127.0.0.1 ([127.0.0.1])             by ZPH (JAMES SMTP Server 2.3.1) with SMTP ID 693             for <[email protected]>;             Wed, 9 Jul 2008 19:58:38 +0800 (CST)   Date: Wed, 9 Jul 2008 19:58:38 +0800 (CST)   From: [email protected]   To: [email protected]   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!  0: [email protected]	I hava my own mail server
Return-Path: <[email protected]>
Delivered-To: [email protected]
Received: from 127.0.0.1 ([127.0.0.1])
by ZPH (JAMES SMTP Server 2.3.1) with SMTP ID 693
for <[email protected]>;
Wed, 9 Jul 2008 19:58:38 +0800 (CST)
Date: Wed, 9 Jul 2008 19:58:38 +0800 (CST)
From: [email protected]
To: [email protected]
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!



從上面的結果可以看出,該郵件是由[email protected] 發給 [email protected] 的。

多發幾封電子郵件,就會發現,James 的郵件接收是一個棧結構,最近收到的郵件編號爲0,依次類推……
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章