非纯原创 在其他代码上修改而来 可实现发送多个附件 可给多个人发送 用,分割
jar包 mail.jar commons-lang3-3.7.jar commons-io-2.6.jar commons-fileupload-1.3.3.jar
JSP
<%@ page language="java" import="java.util.*" contentType="text/html; charset=GBK" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>EMAIL</title>
</head>
<body>
<div align="center">
<form action="SendAttachment" method="post" ENCTYPE="multipart/form-data" accept-charset="GBK">
收件人 <input type="text" size="40" name="to"><br><br>
<input type="hidden" size="40" name="from" value="xxx@xxx.com" >
<input type="hidden" size="40" name="subject">
附件:<input type="file" name="file" size="28" multiple="multiple" /><br><br>
内容:<textarea rows="6" cols="38" name="content" ></textarea>
<input type="submit" value="Send" />
<input type="reset" value="Cancle" />
</form>
</div>
</body>
</html>
SendAttachment
package com.itth.mail;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.itth.mail.AttachmentSender;
public class SendAttachment extends HttpServlet {
/**
* Constructor of the object.
*/
public SendAttachment() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("GBK");
response.setContentType("text/html;charset=GBK");
URLEncoder.encode("GBK");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC /'-//W3C//DTD HTML 4.01 Transitional//EN/'>");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("GBK");
response.setContentType("text/html;charset=GBK");
URLEncoder.encode("GBK");
PrintWriter out = response.getWriter();
//set the smtp address of sina
String host = "smtp.etrustpower.com";
//set mailbox accountName
String accountName = "wangyinglu@etrustpower.com";
//set mailbox password
String password = "E3oTkDBksSNUcVmd";
//attachment
File uploadedFile = null;
//sender's address
String from = "";
//recipient's address
String to = "";
//mail subject
String subject = "";
//mail content
String content = "";
String fileName= null;
//upload the attachment to the server first
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator items;
String savePath = this.getServletContext().getRealPath("/upload");
File file = new File(savePath);
//判断上传文件的保存目录是否存在
if (!file.exists() && !file.isDirectory()) {
System.out.println(savePath+"目录不存在,需要创建");
//创建目录
file.mkdir();
}
if(isMultipart){
try{
items = upload.parseRequest(request).listIterator();
while(items.hasNext()){
FileItem item = (FileItem) items.next();
if(!item.isFormField()){
//get the name of the upload file
String name = item.getName();
fileName = name.substring(name.lastIndexOf("//")+1,name.length());
//upload the file
uploadedFile = new File(savePath+"/"+fileName); //设置文件保存路径
if(fileName.length()>0){
item.write(uploadedFile); //写入文件
}
// File file=uploadedFile.getAbsoluteFile();
}else if(item.isFormField()){
//get the parameter from the form
if(item.getFieldName().equals("from")){
from = item.getString();
}
else if(item.getFieldName().equals("to")){
to = item.getString();
}
else if(item.getFieldName().equals("subject")){
subject = item.getString();
}
else if(item.getFieldName().equals("content")){
content =item.getString();
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
//System.out.println(to);
File[] fs = file.listFiles(); //遍历上传文件夹中所有的文件
/*for (File f : fs){
System.out.println(f.getName()+" name");
System.out.println(f.getPath()+" path");
} */
List<String> attachment1=new ArrayList<String>();
//set mail info
AttachmentSender sender = new AttachmentSender(host,accountName,password);
sender.setFrom(from);
sender.setSubject(subject);
//sender.setTo(a);
sender.Address(to);
sender.setContent(content);
if(uploadedFile != null){
for (File f : fs){
String attachment = f.getPath();
attachment1.add(attachment);
// System.out.println(attachment+" attachment");
}
/* for(String a : attachment1){
System.out.println(a+" attachment1");
}*/
sender.addAttachMent(attachment1);
}
//print the result
if(sender.send()){
out.print("Send mail successfully!");
}
else{
out.print("Send mail failed!");
}
//delete the file on the server after send the mail
if(uploadedFile.exists()) //删除发送过的附件
for (File f : fs){
f.delete();
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
AttachmentSender
package com.itth.mail;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
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 sun.misc.BASE64Encoder;
public class AttachmentSender {
private MimeMessage message;
private Properties props;
private Session session;
private MimeMultipart mp;
private String name = "";
private String password = "";
private static InternetAddress[] address=null;
/**
* complete the initialization
* @param host
* @param name
* @param password
*/
public AttachmentSender(String host, String name, String password){
this.name = name;
this.password = password;
props = System.getProperties();
//set the SMTP host
props.put("mail.smtp.host", host);
//set SMTP authorization
props.put("mail.smtp.auth", "true");
//get the mail session
MyAuthenticator auth = new MyAuthenticator(name,password);
session = Session.getDefaultInstance(props,auth);
//create MIME mail object
message = new MimeMessage(session);
mp = new MimeMultipart();
}
/**
* set mail sender
* @param from
*/
public void setFrom(String from){
try {
message.setFrom(new InternetAddress(from));
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* set mail recipient
* @param address
*/
/*public void setTo(InternetAddress[] address){
try {
//System.out.println(to+"2");
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address));
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} */
public static InternetAddress[] Address(String to){
//多个接收账号
try {
List list = new ArrayList();//不能使用string类型的类型,这样只能发送一个收件人
String []median=to.split(",");//对输入的多个邮件进行逗号分割
for(int i=0;i<median.length;i++){
list.add(new InternetAddress(median[i]));
System.out.println(median[i]);
}
address =(InternetAddress[])list.toArray(new InternetAddress[list.size()]);
} catch (AddressException e) {
e.printStackTrace();
}
return address;
}
/**
* set mail subject
* @param subject
* @throws UnsupportedEncodingException
*/
public void setSubject(String subject) throws UnsupportedEncodingException{
try {
message.setSubject(MimeUtility.encodeText("任务系统") );
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* set the mail content
* @param content
*/
public void setContent(String content){
try{
BodyPart bp = new MimeBodyPart();
bp.setContent(content,"text/html");
mp.addBodyPart(bp);
}catch(Exception e){
e.printStackTrace();
}
}
/**
* attach the file
* @param filename
*/
public void addAttachMent(List<String> attachment1){
try{
//System.out.println(filename);
int i=0;
for(String a : attachment1){
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(a);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(MimeUtility.encodeText(fileds.getName(),MimeUtility.mimeCharset("gbk"), null));
mp.addBodyPart(bp,i);
i++;
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* send mail
* @return
*/
public boolean send(){
try{
message.setContent(mp);
message.saveChanges();
//create SMTP sender object
Transport transport = session.getTransport("smtp");
//get the connection with server
transport.connect((String) props.get("mail.smtp.host"),name,password);
//send the mail via server
transport.sendMessage(message, address);
transport.close();
return true;
}catch(NoSuchProviderException e){
e.printStackTrace();
return false;
}catch (MessagingException e){
e.printStackTrace();
return false;
}
}
}
/**
* send mail
* @return
*/
public boolean send(){
try{
message.setContent(mp);
message.saveChanges();
//create SMTP sender object
Transport transport = session.getTransport("smtp");
//get the connection with server
transport.connect((String) props.get("mail.smtp.host"),name,password);
//send the mail via server
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
return true;
}catch(NoSuchProviderException e){
e.printStackTrace();
return false;
}catch (MessagingException e){
e.printStackTrace();
return false;
}
}
}
MyAuthenticator
package com.itth.mail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MyAuthenticator extends Authenticator{
String name;
String password;
public MyAuthenticator(String name, String password){
this.name = name;
this.password = password;
getPasswordAuthentication();
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(name,password);
}
}