JavaMail的介紹
JavaMail,顧名思義,提供給開發者處理電子郵件相關的編程接口。它是Sun發布的用來處理email的API。它可以方便地執行一些常用的郵件傳輸。
雖然JavaMail是Sun的API之一,但它目前還沒有被加在標准的java開發工具包中(Java Development Kit),這就意味着你在使用前必須另外下載JavaMail文件。除此以外,你還需要有Sun的JavaBeans Activation Framework (JAF)。JavaBeans Activation Framework的運行很復雜,在這里簡單的說就是JavaMail的運行必須得依賴於它的支持。在Windows 2000下使用需要指定這些文件的路徑,在其它的操作系統上也類似。
1.郵件協議
主要包括:
SMTP協議:Simple Mail Transfer Protocol,即簡單郵件傳輸協議,用於發送電子郵件
POP3協議:Post Office Protocol 3,即郵局協議的第三個版本,用於接收郵件
IMAP協議:Internet Message Access Protocol,即互聯網消息訪問協議,是POP3的替代協議
2.搭建James郵件服務器
James是Apache的一個開源項目,純Java實現
搭建James服務器
1)下載apache-james-2.3.2.zip解壓

2)運行bin目錄下的run.bat即可啟動服務器
3) 通過apps\james\SAR-INF\config.xml配置服務器
一定注意:先到bin下run一道 放如非中文目錄 得再控制面板開啟Telnet客戶端
Telnet localhost 4555
3.安裝OutLook[郵件客戶端]
產品秘鑰:PQDV9-GPDV4-CRM4D-PHDTH-4M2MT
創建用戶賬號
一、使用telnet連接James的Remote Administration Tool
二、以管理員身份登錄
三、使用adduser命令添加用戶
4.配置outlook郵件客戶端
為了方便查看,可以配置Microsoft Outlook郵件客戶端,保證James郵件服務器是啟動狀態,啟動Microsoft Outlook.
選擇“工具”->“選項”,打開“選項”面板。選擇“郵件設置”並點擊“電子郵件賬戶”,打開“賬號設置”面板。在“電子郵件”選項卡下新建郵件賬戶
5.案例[搭建James郵件服務器]
需求說明:
在本機搭建James郵件服務器,自定義服務器的名稱。
創建兩個測試用戶。
在Microsoft Outlook中配置其中一個測試用戶為Outlook郵件賬戶

6.使用JavaMail發送電子郵件(案例)
需求:
使用JavaMail技術,實現從A賬戶給B賬戶發送一封電子郵件,標題為“會議通知”,郵件內容為“XX你好!請於明天下午16:00 准時到B01會議室召開技術討論會。”通過Outlook 客戶端查看郵件程序發送的郵件是否發送成功
關鍵代碼:
創建一個類EmailAuthenticator並繼承自Authenticator,並植入用戶名和密碼
package cn.mail; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class EmailAuthenticator extends Authenticator { private String username; private String userpass; public void setUsername(String username) { this.username = username; } public void setUserpass(String userpass) { this.userpass = userpass; } public EmailAuthenticator() { } public EmailAuthenticator(String username, String userpass) { this.username = username; this.userpass = userpass; } public PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(username,userpass); } }
創建Mail類設置郵件信息:
package cn.mail; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class Mail { private String mailServer,from,to,mailSubject,mailContent; private String username,password; public Mail(){ //設置郵件信息 //進行認證登錄的用戶名 username="zt@mail.com"; //認證密碼 password="zt"; //認證的郵箱對應的郵件服務器 mailServer="192.168.17.173"; //發件人信息 from="zt"; //收件人信息 to="jpp@mail.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(); } } }
測試類:
package cn.mail; public class Test { public static void main(String[] args) { Mail mail=new Mail(); mail.send(); System.out.println("success!"); } }


發送帶附件的Mail

MailWithAttachment:
package cn.bdqn; import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import org.springframework.core.io.ClassPathResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; 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("zt@mail.com"); helper.setTo("jpp@mail.com"); 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); } }
測試類:
package cn.bdqn; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MailTest { public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); /*測試帶附件的郵件*/ try{ MailWithAttachment mailWithAttach = (MailWithAttachment)context.getBean("mailWithAttachment"); mailWithAttach.send(); }catch(Exception e){ System.out.print(e.toString()); } } }
applicationContext.xml:大配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="192.168.17.173"></property><!-- 服務器 --> <property name="port" value="25"></property><!-- 端口 --> <property name="username" value="jpp"></property><!-- 用戶名 --> <property name="password" value="jpp"></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="mailWithAttachment" class="cn.bdqn.MailWithAttachment"> <property name="mailSender" ref="mailSender"></property> </bean> </beans>

發送帶圖片的mail
Mail.com
package cn.bdqn.pojo; import java.io.File; public class Mail { private String from; private String to; private String subject; private String content; private File file; private String fileName; public Mail(){} public Mail(String from, String to, String subject, String content, File file, String fileName){ this.from = from; this.to = to; this.subject = subject; this.content = content; this.file = file; this.fileName = fileName; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } }
MailService:
package cn.bdqn.service; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import cn.bdqn.pojo.Mail; public class MailService { private JavaMailSender mailSender; public void setMailSender(JavaMailSender mailSender) { this.mailSender = mailSender; } public void sendMail(Mail mail){ try{ MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); helper.setFrom("jpp@mail.com"); helper.setTo(mail.getTo()); helper.setSubject(mail.getSubject()); helper.setText(mail.getContent()); //(1)要直接使用帶后綴的文件名全稱, (2)需要處理中文亂碼問題 helper.addAttachment(MimeUtility.encodeWord(mail.getFileName()),mail.getFile()); mailSender.send(mimeMessage); }catch(Exception e){ e.printStackTrace(); } } }
SendMailAction:
package cn.bdqn.action; import java.io.File; import cn.bdqn.pojo.Mail; import cn.bdqn.service.MailService; import com.opensymphony.xwork2.ActionSupport; public class SendMailAction extends ActionSupport{ private static final long serialVersionUID = 1L; private MailService mailService =null; private String from; private String to; private String subject; private String content; private File upload; private String uploadFileName; @Override public String execute() throws Exception { Mail mail = new Mail(getFrom(),getTo(),getSubject(),getContent(),getUpload(),getUploadFileName()); mailService.sendMail(mail); return "success"; } public void setMailService(MailService mailService) { this.mailService = mailService; } public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } }
applicationContext.xml:大配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="192.168.8.71"></property><!-- 服務器 --> <property name="port" value="25"></property><!-- 端口 --> <property name="username" value="jpp"></property><!-- 用戶名 --> <property name="password" value="jpp"></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="mailService" class="cn.bdqn.service.MailService"> <property name="mailSender" ref="mailSender"></property> </bean> </beans>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <constant name="struts.i18n.encoding" value="UTF-8"/> <package name="default" namespace="/" extends="struts-default"> <action name="sendmailAction" class="cn.bdqn.action.SendMailAction"> <result name="success">/sendmail_success.jsp</result> </action> </package> </struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- struts2的配置文件 --> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <!-- <url-pattern>*.action</url-pattern> --> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring的配置信息 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </filter-class> </filter> --> <!-- <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> --> </web-app>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@taglib uri="/struts-tags" prefix="s"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>郵件發送頁</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <H2>郵件發送</H2><br> <s:form action="sendmailAction" enctype="multipart/form-data" method="post"> <s:textfield name="from" label="發件人" value="tina@mail.com"/> <s:textfield name="to" label="收件人"/> <s:textfield name="subject" label="主題"/> <s:textarea name="content" label="內容"/> <s:file name="upload" lable="選擇附件"/> <s:submit name="submit" value="發送郵件"/> </s:form> </body> </html>
sendmail_success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>成功頁</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <H2>郵件發送成功!</H2> </body> </html>




