您的位置:首页 > 编程语言 > Java开发

使用javaMail来发送和接收带附件的邮件

2014-01-15 16:33 609 查看
使用javaMail发送(文本支持HTML)邮件

内容为HTML网页的邮件叫做HTML型邮件,它与文本型邮件的主要区别在于MIME类型的不同,一个为“text/html”,一个为“text/plain”。本文将使用javaMail发送HTML型邮件。用户通过在邮件书写页面attachMail.jsp填写表单然后提交给sendMail.jsp,,由sendMail.jsp调用实体bean实现邮件的发送。。

attachMail.jsp:

<%@ page
language="java"
import="java.util.*"
pageEncoding="gb2312"%>
<%
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>

<title>My JSP 'index.jsp' starting page</title>
<meta
http-equiv="content-type"content="text/html;charset=gb2312">
<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="Thisis my page">
<!--
<link rel="stylesheet" type="text/css"href="styles.css">
-->
</head>

<body>
<h2>发送带附件HTML型邮件</h2><hr>
<form
name="form1"method="post"
action="sendMail.jsp">
SMTP服务器:<input
type="text"
id="SMTPHost"name="SMTPHost"
/><br>
登 录账 号:<input
type="text"
id="user"
name="user"/><br>
登 录密 码:<input
type="text"
id="password"
name="password"/><br>
<hr>
发件人邮箱:<input
type="text"
id="from"name="from"
/><br>
收件人邮箱:<input
type="text"
id="to"name="to"
/><br>
邮 件标 题:<input
type="text"
id="subject"
name="subject"/><br>
邮 件内 容:<textarea
id="content"name="content"
rows="5"
cols="40"></textarea><br>
<br>
附 件文 件:<input
type="file"
id="filename"
name="filename"/><br><br>

<input
type="submit"name="submit"
value="发送">
<input
type="reset"name="reset"
value="重置">

</form>
</body>
</html>

SendAttachMail.java

package test;

importjava.util.Date;

importjava.util.Properties;

importjavax.activation.DataHandler;

importjavax.activation.FileDataSource;

importjavax.mail.BodyPart;

importjavax.mail.Message;

importjavax.mail.Multipart;

import javax.mail.Session;

importjavax.mail.Transport;

importjavax.mail.internet.InternetAddress;

importjavax.mail.internet.MimeBodyPart;

importjavax.mail.internet.MimeMessage;

importjavax.mail.internet.MimeMultipart;

public classSendAttachMail {

String SMTPHost =""; //SMTP服务器

String user = ""; //登录SMTP服务器的账号

String password ="";//登录SMTP服务器的密码

String from =""; //发件人邮箱

String to =""; //收件人游戏

String subject =""; //邮件标题

String content =""; //邮件内容

String filename ="";//附件文件名

public SendAttachMail(){

}

public String getSMTPHost() {

return SMTPHost;

}

public void setSMTPHost(String host) {

SMTPHost = host;

}

public String getUser() {

return user;

}

public void setUser(String user) {

this.user = user;

}

public String getPassword() {

return password;

}

public void setPassword(String password){

this.password = password;

}

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 getFilename() {

return filename;

}

public void setFilename(String filename){

this.filename = filename;

}

//发送邮件

public boolean send(){

//创建一个属性对象

Properties props = newProperties();

//指定SMTP服务器

props.put("mail.smtp.host",SMTPHost);

//指定是否需要SMTP验证

props.put("mail.smtp.auth","true");

try{

//创建一个授权验证对象

SmtpAuth auth = newSmtpAuth();

auth.setAccount(user,password);

//创建一个session对象

Session mailSession =Session.getDefaultInstance(props,auth);

mailSession.setDebug(true);

//创建一个MimeMessage对象

MimeMessage message = newMimeMessage(mailSession);

//指定发件人游戏

message.setFrom(newInternetAddress(from));

//指定收件人邮箱

message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));

//指定邮件主题

message.setSubject(new String(subject.getBytes("ISO8859-1"), "gb2312"));

//指定邮件发送日期

message.setSentDate(newDate());

//指定邮件优先级 1:紧急,3:普通,5:缓慢

message.setHeader("X-Priority","1");

message.saveChanges();

//新建一个MimeMultipart对象用来存放多个BodyPart对象

Multipart container = newMimeMultipart();

//新建一个存放信件内容的BodyPart对象

BodyPart textBodyPart = newMimeBodyPart();

//给BodyPart对象设置内容和格式、编码格式

textBodyPart.setContent(new String(content.getBytes("ISO8859-1"), "gb2312"),"text/html;charset=gb2312");

//将含有信件内容的BodyPart加入到MimeMultipart对象中

container.addBodyPart(textBodyPart);

//新建一个存放信件附件的BodyPart对象

BodyPart fileBodyPart = newMimeBodyPart();

//处理邮件中附件文件名的中文问题

filename = new String(filename.getBytes("ISO8859-1"), "gb2312");

String filepath ="C:\\Users\\Administrator\\Desktop\\"+filename;

//将本地文件作为附件

FileDataSource fds = newFileDataSource(filepath);

fileBodyPart.setDataHandler(newDataHandler(fds));

//处理邮件中附件文件名的中文问题

String attachName =fds.getName();

attachName = newString(attachName.getBytes("gb2312"),"ISO8859-1");

//设定附件文件名

fileBodyPart.setFileName(attachName);

//将附件的BodyPart对象加入到container中

container.addBodyPart(fileBodyPart);

//将container作为消息对象的内容

message.setContent(container);

//创建一个Transport对象

Transport transport =mailSession.getTransport("smtp");

System.out.println(SMTPHost);

System.out.println(user);

System.out.println(password);

//连接SMTP服务器

transport.connect(SMTPHost,user,password);

//发送邮件

transport.send(message,message.getAllRecipients());

transport.close();

return true;

}catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

return false;

}

}

}

sendMail.jsp

<%@ page
language="java"
import="java.util.*"
pageEncoding="gb2312"%>
<%@ page
import="test.SendAttachMail"%>
<jsp:useBean
id="mySend"
class="test.SendAttachMail"></jsp:useBean>
<jsp:setProperty
property="*"
name="mySend"/>
<%
boolean status = mySend.send();
if(status){
out.println("恭喜你。发送邮件成功!");
}else{
out.println("对不起发送邮件失败");
}
%>

附带截图:attachMail.jsp



附带截图:SendAttachMail.java



附带截图:sendMail.jsp



Sina邮箱:



使用javaMail接收(文本支持HTML)邮件

receiveMail.jsp:

<%@ page
language="java"
import="java.util.*"
pageEncoding="gb2312"%>
<%
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>

<title>My JSP 'index.jsp' starting page</title>
<meta
http-equiv="content-type"content="text/html;charset=gb2312">
<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="Thisis my page">
<!--
<link rel="stylesheet" type="text/css"href="styles.css">
-->
</head>

<body>
<h2>收取邮件</h2><hr>
<form
name="form1"method="post"
action="MailList.jsp">
POP3服务器:<input
type="text"
id="POP3Host"name="POP3Host"
/><br>
登 录账 号:<input
type="text"
id="user"
name="user"/><br>
登 录密 码:<input
type="text"
id="password"
name="password"/><br>

<input
type="submit"name="submit"
value="发送">
<input
type="reset"name="reset"
value="重置">

</form>
</body>
</html>

GetMail.java:

package test;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Enumeration;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Properties;

import javax.mail.BodyPart;

import javax.mail.FetchProfile;

import javax.mail.Folder;

import javax.mail.Header;

import javax.mail.Message;

import javax.mail.Multipart;

import javax.mail.Part;

import javax.mail.Session;

import javax.mail.Store;

public class GetMail {

StringPOP3Host = ""; // POP3Host服务器

Stringuser = ""; // 登录SMTP服务器的账号

Stringpassword = "";// 登录SMTP服务器的密码

Sessionsession = null;

Folderfolder = null;

Storestore = null;

publicGetMail() {

}

publicString getPOP3Host() {

returnPOP3Host;

}

publicvoid setPOP3Host(String host) {

POP3Host= host;

}

publicString getUser() {

returnuser;

}

publicvoid setUser(String user) {

this.user= user;

}

publicString getPassword() {

returnpassword;

}

publicvoid setPassword(String password) {

this.password= password;

}

publicSession getSession() {

returnsession;

}

publicvoid setSession(Session session) {

this.session= session;

}

publicFolder getFolder() {

returnfolder;

}

publicvoid setFolder(Folder folder) {

this.folder= folder;

}

publicStore getStore() {

returnstore;

}

publicvoid setStore(Store store) {

this.store= store;

}

//连接邮件服务器

publicvoid connect() throws Exception {

//创建一个授权验证对象

POP3Authauth = new POP3Auth();

auth.setAccount(user,password);

Propertiesprop = new Properties();

System.out.println(POP3Host);

prop.put("mail.pop3.host",POP3Host);

//取得一个session对象

session= Session.getDefaultInstance(prop, auth);

//取得一个Store对象

store= session.getStore("pop3");

System.out.println(user+"================"+password);

store.connect(POP3Host,user, password);

//取得一个Folder对象

folder= store.getDefaultFolder().getFolder("INBOX");

folder.open(Folder.READ_ONLY);

}

//获取所有邮件的列表

publicMessage[] getAllMail() throws Exception {

//建立POP3连接

connect();

//取得所有的Message对象

Message[]msg = folder.getMessages();

FetchProfileprofile = new FetchProfile();

profile.add(FetchProfile.Item.ENVELOPE);

folder.fetch(msg,profile);

returnmsg;

}

//取得邮件列表的信息

publicList getMailInfo(Message[] msg) throws Exception {

Listresult = new ArrayList();

Mapmap = null;

Multipartmp = null;

BodyPartpart = null;

Stringdisp = null;

SimpleDateFormatfmt = new SimpleDateFormat("yyyy 年 MM 月 dd 日 hh:mm:ss");

Enumerationenmu = null;

for(int i = 0; i < msg.length; i++) {

map= new HashMap();

//读取邮件ID

enmu= msg[i].getAllHeaders();

Headerh = null;

while(enmu.hasMoreElements()) {

h= (Header) enmu.nextElement();

if(h.getName().equals("Message-ID")) {

map.put("ID",h.getValue());

}

}

//读取邮件标题

map.put("subject",msg[i].getSubject());

// new String(subject.getBytes("ISO8859-1"), "gb2312");

Stringsender = new String(msg[i].getFrom()[0].toString().getBytes("ISO8859-1"),

"GBK");

Stringdate = "";

if(msg[i].getSentDate()!=null){

date= fmt.getInstance().format(msg[i].getSentDate());

}else{

date= "";

}

//读取发件人

map.put("sender",sender);

// map.put("sender", msg[i].getFrom()[0].toString());

//读取发送时间

map.put("senddate",date);

//读取邮件大小

map.put("size",new Integer(msg[i].getSize())+"K");

//读取附件

map.put("hasAttach","");

//判断是否有附件

if(msg[i].isMimeType("multipart/*")) {

mp= (Multipart) msg[i].getContent();

//遍历每个Miltipart对象

for(int j = 0; j < mp.getCount(); j++) {

part= mp.getBodyPart(j);

disp= part.getDescription();

//如果有附件

if(disp != null && (disp.equals(Part.ATTACHMENT)

||disp.equals(Part.INLINE))) {

System.out.println("++++++++++++++");

map.put("hasAttach","X");

}

}

}

result.add(map);

}

returnresult;

}

//查找指定的邮件

publicMessage findMail(String id) throws Exception {

Message[]msg = getAllMail();

Enumerationenmu = null;

Headerh = null;

for(int i = 0; i < msg.length; i++) {

enmu= msg[i].getAllHeaders();

while(enmu.hasMoreElements()) {

h= (Header) enmu.nextElement();

if(h.getName().equals("Message-ID")

&&(h.getValue().equals(id))) {

returnmsg[i];

}

}

}

returnnull;

}

//读取邮件内容

publicMap readMail(String basePath, String id) throws Exception {

Mapmap = new HashMap();

//找到目标邮件

Messagemsg = findMail(id);

Stringtitle = "";

if(msg.getSubject()!=null){

title= msg.getSubject();

}

//读取邮件标题

map.put("subject",title);

System.out.println(msg.getFrom()[0].toString()+"====");

//读取发件人

map.put("sender",msg.getFrom()[0].toString());

map.put("attach","");

//取得邮件内容

if(msg.isMimeType("text/*")) {

map.put("content",msg.getContent().toString());

}else {

StringBufferresult = new StringBuffer();

Multipartmp = (Multipart) msg.getContent();

BodyPartpart = null;

Stringdisp = null;

//遍历每个Multipart对象

for(int j = 0; j < mp.getCount(); j++) {

part= mp.getBodyPart(j);

disp =part.getDisposition();

//如果有附件

if(disp != null

&&(disp.equals(Part.ATTACHMENT) || disp

.equals(Part.INLINE))){

Stringfilename = part.getFileName();

filename= new String(filename.getBytes("ISO8859-1"),

"gb2312");

map.put("attach",filename);

//下载附件

InputStreamin = part.getInputStream();

filename= basePath + "/" + filename;

FileOutputStreamout = new FileOutputStream(new File(

filename));

byte[]content = new byte[255];

intread = 0;

while((read = in.read(content)) != -1) {

out.write(content);

}

out.close();

in.close();

}else{

result.append(part.getContent().toString());

}

}

map.put("content",result.toString());

}

returnmap;

}

}

MailList.jsp:

<%@ page
language="java"
import="java.util.*"
pageEncoding="gb2312"%>
<%@ page
import="test.GetMail"%>
<jsp:useBean
id="receiver"
class="test.GetMail"
scope="session"></jsp:useBean>
<jsp:setProperty
property="*"
name="receiver"/>
<html>
<head><title>我的收件箱</title></head>
<body>
<h2>我的收件箱</h2><hr>
<table
border=1
width=700>
<tr
height=30
bgcolor=#dddddd>
<td
align = center> 邮件标题</td>
<td
width=150
align = center> 发件人</td>

<td
width=180
align = center> 发件时间</td>

<td
width=80
align = center> 邮件大下</td>

<td
width=50
align = center> 附件</td>

</tr>
<%
//取得邮件列表显示
Iterator it =receiver.getMailInfo(receiver.getAllMail()).iterator();
Map map = null;
//将邮件信息列表显示
while(it.hasNext()){
map = (Map)it.next();
out.println("<tr height=30 valign = middle align=center>");
out.println("<td><a href='readMail.jsp?id="+map.get("ID")+
"'target= '_blank'>"+map.get("subject")+"</a></td>");
out.println("<td>"+map.get("sender")+"</td>");
out.println("<td>"+map.get("senddate")+"</td>");
out.println("<td>"+map.get("size")+"</td>");
out.println("<td>"+map.get("hasAttach")+"</td>");
out.println("</tr>");
}
%>
</table>
</body>

</html>

readMail.jsp:

<%@ page
language="java"
import="java.util.*"
pageEncoding="gb2312"%>
<%@ page
import="test.GetMail"%>
<%
//从session中取出receiver
GetMail receiver = (GetMail)session.getAttribute("receiver");

%>
<html>
<head><title>阅读邮件</title></head>
<body>
<h2>阅读邮件</h2><hr>

<table
border=1
width =700
cellpadding=4>

<%
//取得请求参数
String id = request.getParameter("id");
String basePath = "C:\\Users\\Administrator\\Desktop\\";
//取得指定的邮件内容
Map result = receiver.readMail(basePath,id);
%>

<tr>
<td
width=100
align=right
bgcolor=#dddddd>邮件标题</td>
<td><%=result.get("subject")%></td>
</tr>

<tr>
<td
width=100
align=right
bgcolor=#dddddd>发件人</td>
<td><%=result.get("sender")%></td>
</tr>

<%
String attach = result.get("attach").toString();
//有附件才显示下面一行
if(attach.trim().length()>0){
%>
<tr>
<td
width=100
align=right
bgcolor=#dddddd>附件</td>
<td><a
href="<%=result.get("attach")%>"><%=result.get("attach")%></a></td>
</tr>
<%}
%>

<tr>
<td
width=100
align=right
bgcolor=#dddddd>内容</td>
<td><%=result.get("content")%></td>
</tr>
</table>

</body>

</html>

演示效果:

ReceiveMail.jsp



MailList.jsp



readMail.jsp



备注:附件是写的本地路径,只为演示而已。。请保存在自己的服务器中

遇到的问题:

POP3 未开启

请开启 自己测试邮箱

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: