搭建james郵件伺服器,james郵件伺服器
James是Apache的一個開源項目,純Java實現,Apache james Server作為一個企業級的郵件伺服器,對SMTP,POP3,IMAP等郵件協議提供完整的支援。
1.搭建James伺服器
Apache James 的官方網站為:http://james.apache.org/,當前 Server 的最新版為 2.3.2版. 安裝非常簡單,下載後得到apache-james-2.3.2.zip 檔案,解壓後即可。
在James的bin目錄中包含兩個重要檔案run.bat和run.sh,運行run.bat就可以輕鬆地啟動James郵件伺服器。
啟動後能在控制台看到如下資訊,說明啟動成功:
說明:啟動前請確保您的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”這裡假設改成 mail.com ,那麼他的郵件地址就是 mail.com修改結果如下:
<postmaster>Postmaster@zhaipuhong.com</postmaster> …… <servernames autodetect="false" autodetectIP="false"> <servername>mail.com</servername> </servernames>
3.建立郵件帳號
使用telnet串連James的Remote Administration Tool。開啟一個控制台視窗,輸入telnet smtp.163.com
JAMES Remote Administration Tool 2.3.1 Please enter your login and password Login id: rootPassword:root Welcome root. HELP for a list of commands
建立新使用者的命令是:adduser username password
提示使用者可以通過“HELP”命令來查詢suo9支援的所有命令
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 關閉串連
樣本:
public class Mail { private String mailServer,from,to,mailSubject,mailContent; private String username,password; public Mail(){ //設定郵件資訊 //進行認證登入的使用者名稱 username="123@163.com"; //認證密碼 password="456"; //認證的郵箱對應的郵件伺服器 mailServer="smtp.163.com"; //寄件者資訊 from="123@163.com"; //收件者資訊 to="xxx@126.com"; //郵件標題 mailSubject="嘿嘿"; //郵件內容 mailContent="天不錯!"; } //設定郵件伺服器 @SuppressWarnings("static-access")public void send(){ Properties prop=System.getProperties(); //指定郵件server prop.put("mail.smtp.host", mailServer); //是否開啟認證 prop.put("mail.smtp.auth", "true"); //smtp協議的 prop.put("mail.smtp.port", "25"); //產生Session服務 EmailAuthenticator mailauth=new EmailAuthenticator(username, password); Session mailSession=Session.getInstance(prop,(Authenticator)mailauth); try { //封裝Message對象 Message message=new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); //寄件者 message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));//收件者 message.setSubject(mailSubject); //設定內容(設定字元集處理亂碼問題) message.setContent(mailContent,"text/html;charset=gbk"); message.setSentDate(new Date()); //建立Transport執行個體,發送郵件 Transport tran=mailSession.getTransport("smtp"); tran.send(message,message.getAllRecipients()); tran.close(); } catch (Exception e) { e.printStackTrace(); } }}
使用Spring寄送電子郵件
建立SimpleMailMessage
SimpleMailMessage是MailMessage介面的實作類別之一。
import org.springframework.mail.MailSender;import org.springframework.mail.SimpleMailMessage;public class Mail { private MailSender mailSender; public void setMailSender(MailSender mailSender) { this.mailSender = mailSender; } public void send(){ SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("dzw@mail.com"); message.setTo("tom"); message.setSubject("問好"); message.setText("好久不見,最近好嗎?"); mailSender.send(message); }}
applicationContext.xml
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="192.168.15.22"></property><!-- 伺服器 --> <property name="port" value="25"></property><!-- 連接埠 --> <property name="username" value="dzw@mail.com"></property><!-- 使用者名稱 --> <property name="password" value="dzw"></property><!-- 密碼 --> <property name="protocol" value="smtp" ></property><!-- 協議 --> <property name="defaultEncoding" value="utf-8"></property><!-- 預設編碼 --> <property name="javaMailProperties"> <props> <!-- 設定SMTP伺服器需要使用者驗證 --> <prop key="mail.smtp.auth">true</prop> </props> </property> </bean> <bean id="mail" class="cn.bdqn.Mail"> <property name="mailSender" ref="mailSender"></property> </bean> <bean id="mailWithAttachment" class="cn.bdqn.MailWithAttachment"> <property name="mailSender" ref="mailSender"></property> </bean> <bean id="mailWithHtml" class="cn.bdqn.MailWithHTML"> <property name="mailSender" ref="mailSender"></property> </bean></beans>
發送HTML格式的電子郵件
HTMl格式的文本屬於MIME類型,需要MimeMessageHelper類的支援
public class MailWithHTML { private JavaMailSender mailSender; //必須使用 JavaMailSender public void setMailSender(JavaMailSender mailSender) { this.mailSender = mailSender; } public void send() throws MessagingException,IOException{ MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); helper.setFrom("dzw@mail.com"); helper.setTo("tom"); helper.setSubject("歡迎來到員工社區"); StringBuffer sb = new StringBuffer(); sb.append("<html><head>"); sb.append("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">"); sb.append("<head><body>"); sb.append("<font color='blue' size='5' face='Arial'>"); sb.append("尊敬的jerry您好:</font><br/><br/>"); sb.append(" "); sb.append("<font color='black' size='4' face='Arial'>"); sb.append("恭喜您在員工社區註冊帳號成功!請妥善保管您的帳號," + "如果登入時忘記密碼,可以在網站登入頁找回。<br/>"); sb.append("<br/><br/>系統管理員</font>"); //增加內嵌圖片設定 sb.append("<br/><img src=\"cid:photo\"></img>"); sb.append("</body></html>"); helper.setText(sb.toString(),true); //增加內嵌檔案 ClassPathResource file = new ClassPathResource("/cn/bdqn/attachfiles/Quartz.png"); helper.addInline("photo", file); mailSender.send(mimeMessage); }}
通過setText()設定html參數為true,郵件內容就可以顯示HTML頁面。在HTML頁面中,需要設定content屬性,通過“text/html;charset=utf-8”
public class MailWithAttachment { private JavaMailSender mailSender; //必須使用 JavaMailSender public void setMailSender(JavaMailSender mailSender) { this.mailSender = mailSender; } public void send() throws MessagingException,IOException{ MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); helper.setFrom("dzw@mail.com"); helper.setTo("tom"); helper.setSubject("問好"); helper.setText("好久不見,最近好嗎?"); //添加附件1 ClassPathResource file1 = new ClassPathResource( "/cn/bdqn/attachfiles/test.doc"); helper.addAttachment(file1.getFilename(), file1.getFile()); //添加附件2:附件的檔案名稱為中文時,需要對檔案名稱進行編碼轉換,解決亂碼問題 ClassPathResource file2 = new ClassPathResource( "/cn/bdqn/attachfiles/附件測試檔案.doc"); helper.addAttachment(MimeUtility.encodeWord(file2.getFilename()),file2.getFile()); mailSender.send(mimeMessage); }}
測試類別
public class MailTest { public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); /*測試簡單郵件*/ Mail mail = (Mail)context.getBean("mail"); mail.send(); /*測試帶附件的郵件*/ try{ MailWithAttachment mailWithAttach = (MailWithAttachment)context.getBean("mailWithAttachment"); mailWithAttach.send(); }catch(Exception e){ System.out.print(e.toString()); } /*測試HTML格式的郵件*/ try{ MailWithHTML mailWithHtml = (MailWithHTML)context.getBean("mailWithHtml"); mailWithHtml.send(); }catch(Exception e){ System.out.print(e.toString()); } }}