使用Java發(fā)送帶附件的附件的示例
這里使用的是JavaMail技術(shù),前臺(tái)使用了fckeditor做郵件美化,由于只是示例,后臺(tái)發(fā)送時(shí)只是將郵件保存在本地,但是可以查看,如果需要實(shí)際發(fā)送,請(qǐng)參考我的其他博客文章,我寫了很多關(guān)于郵件發(fā)送的示例!

JSP頁(yè)面頁(yè)面除了引用fckeditor外,要注意我們是需要發(fā)送附件的:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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>發(fā)送郵件</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script type="text/javascript" src="fckeditor/fckeditor.js"></script>
<script type="text/javascript">
window.onload=function(){
var oFCKeditor = new FCKeditor( 'content' ) ;
//編譯器基本路徑
oFCKeditor.BasePath = "/pro_04/fckeditor/";
//高度
oFCKeditor.Width=800;
//寬度
oFCKeditor.Height=300;
//工具條集合名稱(Default,Basic或自己制定,關(guān)于FCK的使用,博客內(nèi)有專門文章)
//具體的配置可以將默認(rèn)顯示出來然后到FCK目錄里的fckconfig.js里
//FCKConfig.ToolbarSets["Default"]數(shù)組中去除不要的功能一共63個(gè)功能屬性
//oFCKeditor.ToolbarSet="Basic";
oFCKeditor.ReplaceTextarea() ;
}
</script>
</head>
<body>
<!-- 注意表單格式,這里需要上傳附件 -->
<form action="SendMailServlet" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>收件人:</td>
<td><input type="text" name="to" /></td>
</tr>
<tr>
<td>抄送:</td>
<td><input type="text" name="copy" /></td>
</tr>
<tr>
<td>主題:</td>
<td><input type="text" name="title" /></td>
</tr>
<tr>
<td>信件內(nèi)容:</td>
<td><textarea rows="10" cols="20" name="content" id="content"></textarea></td>
</tr>
<tr>
<td>附件:</td>
<td><input type='file' name='ufile' /></td>
</tr>
<tr>
<td>背景音樂:</td>
<td><input type='file' name='umusic' /></td>
</tr>
<tr>
<td>背景圖片:</td><!-- 背景圖片我們后臺(tái)自己準(zhǔn)備 -->
<td>
<select name="bgimg">
<option value="1">一號(hào)</option>
<option value="2">二號(hào)</option>
</select>
</td>
</tr>
<tr align="right">
<td colspan="2"><input type="submit" value="發(fā) 送"></td>
</tr>
</table>
</form>
</body>
</html>
為了防止亂碼,會(huì)經(jīng)過一個(gè)過濾器:
package org.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* 過濾器防止亂碼
* @說明
* @author cuisuqiang
* @version 1.0
* @since
*/
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
然后到Servlet處理附件和信息,這里就不做異常處理了,出錯(cuò)直接報(bào)錯(cuò):
package org.servlet;
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.entity.MailModel;
import org.mail.SendMail;
/**
* 接收表單,處理附件,組裝郵件對(duì)象,并調(diào)用發(fā)送接口
* @說明 在C盤創(chuàng)建臨時(shí)文件
* @author cuisuqiang
* @version 1.0
* @since
*/
@SuppressWarnings("serial")
public class SendMailServlet extends HttpServlet {
@SuppressWarnings( { "unchecked", "deprecation" })
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 建立磁盤工廠
FileItemFactory factory = new DiskFileItemFactory();
// 表單域
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
String bgimg = "1"; // 默認(rèn)是第一個(gè)背景圖片
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
MailModel mail = new MailModel();
InputStream is = null;
for (FileItem item : items) {
if (!item.isFormField()) { // 如果是附件
if (item.getSize() > 0) {
is = item.getInputStream();
String filename = "";
if (item.getName().indexOf("\\") == -1) {
filename = "c:\\tmp\\" + item.getName();
} else {
filename = "c:\\tmp\\" + item.getName().substring(item.getName().lastIndexOf("\\"));
}
if (is.markSupported()) {
System.out.println("沒有上傳文件或文件已經(jīng)刪除");
} else {
File file = new File(filename);
FileOutputStream fos = new FileOutputStream(file); // 建立輸出流
byte[] buffer = new byte[8192]; // 每次讀8K字節(jié),大文件上傳沒有問題
int count = 0;
while ((count = is.read(buffer)) > 0) { // 循環(huán)寫入到硬盤
fos.write(buffer, 0, count);
}
fos.close(); // 關(guān)閉輸入輸出流
is.close();
if (item.getFieldName().equals("ufile")) {
mail.setFilePath(filename);
} else if (item.getFieldName().equals("umusic")) {
mail.setMusicPath(filename);
}
}
}
} else { // 處理文本信息
if (item.getFieldName().equals("title")) {
mail.setTitle(item.getString("UTF-8"));
} else if (item.getFieldName().equals("content")) {
mail.setContext(item.getString("UTF-8"));
} else if (item.getFieldName().equals("to")) {
mail.setTo(item.getString("UTF-8"));
} else if (item.getFieldName().equals("copy")) {
mail.setCopy(item.getString("UTF-8"));
} else if (item.getFieldName().equals("bgimg")) {
bgimg = item.getString("UTF-8");
}
}
}
String bgPath = request.getRealPath("/") + "\\images\\bg" + bgimg + ".jpg";
mail.setBgPath(bgPath);
try {
SendMail.sendMail(mail);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect(request.getContextPath() + "/sendmail.jsp");
}
}
這里也沒有驗(yàn)證,接收到信息后組裝一個(gè)郵件實(shí)體對(duì)象,傳遞到發(fā)送接口中發(fā)送:
實(shí)體,我就不寫get和set方法了:
package org.entity;
/**
* 一封郵件的對(duì)象
* @說明
* @author cuisuqiang
* @version 1.0
* @since
*/
public class MailModel {
/**
* 主鍵
*/
private int id;
/**
* 郵件標(biāo)題
*/
private String title;
/**
* 發(fā)送給誰(shuí)
*/
private String to;
/**
* 背景圖片地址
*/
private String bgPath;
/**
* 抄送給誰(shuí)
*/
private String copy;
/**
* 郵件內(nèi)容
*/
private String context;
/**
* 附件地址
*/
private String filePath;
/**
* 背景音樂地址
*/
private String musicPath;
}
然后我們來看看核心處理類:
package org.mail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import org.entity.MailModel;
/**
* 發(fā)送一封郵件
* @說明 注意這里并沒有實(shí)際發(fā)送而是保存在了C盤臨時(shí)文件中,真是發(fā)送的話,請(qǐng)參考我的博客
* @author cuisuqiang
* @version 1.0
* @since
*/
public class SendMail {
public static void sendMail(MailModel mail) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props);
Message message = new MimeMessage(session);
InternetAddress from = new InternetAddress();
from.setPersonal(MimeUtility.encodeText("風(fēng)中落葉<cuisuqiang@163.com>"));
message.setFrom(from);
InternetAddress to = new InternetAddress(mail.getTo());
message.setRecipient(Message.RecipientType.TO, to);
// 是否抄送
if (null != mail.getCopy() && !"".equals(mail.getCopy())) {
InternetAddress copy = new InternetAddress(mail.getCopy());
message.setRecipient(Message.RecipientType.CC, copy);
}
message.setSubject(MimeUtility.encodeText(mail.getTitle()));
message.setSentDate(new Date());
// 指定為混合關(guān)系
MimeMultipart msgMultipart = new MimeMultipart("mixed");
message.setContent(msgMultipart);
MimeBodyPart content = new MimeBodyPart();
msgMultipart.addBodyPart(content);
// 依賴關(guān)系
MimeMultipart bodyMultipart = new MimeMultipart("related");
content.setContent(bodyMultipart);
MimeBodyPart htmlPart = new MimeBodyPart();
// 組裝的順序非常重要
bodyMultipart.addBodyPart(htmlPart);
MimeBodyPart in_bg = new MimeBodyPart();
bodyMultipart.addBodyPart(in_bg);
DataSource bgsou = new FileDataSource(mail.getBgPath());
DataHandler bghd = new DataHandler(bgsou);
in_bg.setDataHandler(bghd);
in_bg.setHeader("Content-Location", "bg.jpg");
// 是否使用了背景音樂
if (null == mail.getMusicPath() || "".equals(mail.getMusicPath())) {
String start = "<html><body background='bg.jpg'>";
String end = "</body></html>";
htmlPart.setContent(start + mail.getContext() + end,"text/html;charset=UTF-8");
} else {
MimeBodyPart in_Part = new MimeBodyPart();
bodyMultipart.addBodyPart(in_Part);
DataSource gifds = new FileDataSource(mail.getMusicPath());
DataHandler gifdh = new DataHandler(gifds);
in_Part.setDataHandler(gifdh);
in_Part.setHeader("Content-Location", "bg.mp3");
String start = "<html><head><bgsound src='bg.mp3' loop='-1'></head><body background='bg.jpg'>";
String end = "</body></html>";
htmlPart.setContent(start + mail.getContext() + end,"text/html;charset=UTF-8");
}
// 組裝附件
if (null != mail.getFilePath() && !"".equals(mail.getFilePath())) {
MimeBodyPart file = new MimeBodyPart();
FileDataSource file_datasource = new FileDataSource(mail
.getFilePath());
DataHandler dh = new DataHandler(file_datasource);
file.setDataHandler(dh);
file.setFileName(MimeUtility.encodeText(dh.getName()));
msgMultipart.addBodyPart(file);
}
message.saveChanges();
// 保存郵件
OutputStream ips = new FileOutputStream("C:\\tmp\\test.eml");
message.writeTo(ips);
ips.close();
System.out.println("------------發(fā)送完畢------------");
// 刪除臨時(shí)文件
if (null != mail.getMusicPath() && !"".equals(mail.getMusicPath())) {
File file = new File(mail.getMusicPath());
file.delete();
}
if (null != mail.getFilePath() && !"".equals(mail.getFilePath())) {
File file = new File(mail.getFilePath());
file.delete();
}
}
}
我們把郵件發(fā)送了C盤,可以到C盤查看,如果需要實(shí)際發(fā)送,可以參考我的其他博客,有專門說明!

相關(guān)文章
關(guān)于postman傳參的幾種格式 list,map 等
這篇文章主要介紹了postman傳參的幾種格式 list,map等,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
關(guān)于Java實(shí)現(xiàn)HttpServer模擬前端接口調(diào)用
這篇文章主要介紹了關(guān)于Java實(shí)現(xiàn)Http?Server模擬前端接口調(diào)用,Http?協(xié)議是建立在?TCP?協(xié)議之上的協(xié)議,所以能用?TCP?來自己模擬一個(gè)簡(jiǎn)單的?Http?Server?當(dāng)然是可以的,需要的朋友可以參考下2023-04-04
Java中CopyOnWriteArrayList的使用解析
這篇文章主要介紹了Java中CopyOnWriteArrayList的使用解析,CopyOnWriteArrayList適合使用在讀操作遠(yuǎn)遠(yuǎn)大于寫操作的場(chǎng)景里,比如緩存,它不存在擴(kuò)容的概念,每次寫操作都要復(fù)制一個(gè)副本,在副本的基礎(chǔ)上修改后改變Array引用,需要的朋友可以參考下2023-12-12
Java解決計(jì)算相鄰兩個(gè)數(shù)的最大差值的問題
今天給大家?guī)硪坏浪惴}:給定一個(gè)數(shù)組,求如果排序之后,相鄰兩數(shù)的最大差值。要求時(shí)間復(fù)雜度O(N),且要求不能用非基于比較的排序。快來跟隨小編一起學(xué)習(xí)一下如何解決這一問題吧2021-12-12
解決Java?API不能遠(yuǎn)程訪問HBase的問題
這篇文章主要介紹了解決Java?API不能遠(yuǎn)程訪問HBase的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
SpringBoot操作mongo實(shí)現(xiàn)方法解析
這篇文章主要介紹了SpringBoot操作mongo實(shí)現(xiàn)方法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
Spring Boot 實(shí)現(xiàn)https ssl免密登錄(X.509 pki登錄)
這篇文章主要介紹了Spring Boot 實(shí)現(xiàn)https ssl免密登錄(X.509 pki登錄),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Java優(yōu)化for循環(huán)嵌套的高效率方法
這篇文章主要介紹了Java優(yōu)化for循環(huán)嵌套的高效率方法,幫助大家更好的提升java程序性能,感興趣的朋友可以了解下2020-09-09

