I am trying to attach a document file to mail using java. The document to be attached want to select from the user through browse button.
我试图使用java将文档文件附加到邮件。要附加的文档想要通过浏览按钮从用户中进行选择。
I tried the below coding..
我尝试了以下编码..
<form action="emailservlet" enctype="multipart/form-data">
Profile : <input type="file" name="filename"/><br/>
<input type="submit" value="submit">
</form>
And in servlet
在servlet中
File path=new File(fil);
fil=path.getAbsolutePath();
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fil);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fil);
multipart.addBodyPart(messageBodyPart);
But the filenotfound exception is thrown,please help me to rectify this problem...
但抛出了filenotfound异常,请帮我纠正这个问题...
Thanks in advance...
提前致谢...
2 个解决方案
#1
You can do it as:
你可以这样做:
messageBodyPart.setText("This is message body");
messageBodyPart = new MimeBodyPart();
String filename = "/home/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Then send the message using Transport object as:
然后使用Transport对象发送消息:
Transport.send(message);
And, all you need is to update the file path, as you are sending file from client side you can map it directly based on technology servlets/struts2 you were using.
而且,您只需更新文件路径,因为您从客户端发送文件,您可以根据您正在使用的技术servlet / struts2直接映射它。
#2
As you are using the servlet as server side technology then following will be full example to send email with file attachment using servlet.
当您使用servlet作为服务器端技术时,以下将是使用servlet发送带文件附件的电子邮件的完整示例。
1.)Create following Java class with name EmailUtility.java
1.)使用名称EmailUtility.java创建以下Java类
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;
/**
* A utility class for sending e-mail message with attachment.
* @author www.codejava.net
*
*/
public class EmailUtility {
/**
* Sends an e-mail message from a SMTP host with a list of attached files.
*
*/
public static void sendEmailWithAttachment(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message, List<File> attachedFiles)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachedFiles != null && attachedFiles.size() > 0) {
for (File aFile : attachedFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(aFile);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
}
2.) Create following form in your jsp
page
2.)在jsp页面中创建以下表单
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Send an e-mail with attachment</title>
</head>
<body>
<form action="SendMailAttachServlet" method="post" enctype="multipart/form-data">
<table border="0" width="60%" align="center">
<caption><h2>Send New E-mail</h2></caption>
<tr>
<td width="50%">Recipient address </td>
<td><input type="text" name="recipient" size="50"/></td>
</tr>
<tr>
<td>Subject </td>
<td><input type="text" name="subject" size="50"/></td>
</tr>
<tr>
<td>Content </td>
<td><textarea rows="10" cols="39" name="content"></textarea> </td>
</tr>
<tr>
<td>Attach file </td>
<td><input type="file" name="file" size="50" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Send"/></td>
</tr>
</table>
</form>
</body>
</html>
Note that the tag must have attribute enctype="multipart/form-data". If we want to have more attachments we can duplicate the tag.
请注意,标记必须具有enctype =“multipart / form-data”属性。如果我们想要更多附件,我们可以复制标签。
3.) create following servlet class with name SendMailAttachServlet
3.)使用名称SendMailAttachServlet创建以下servlet类
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* A servlet that takes message details from user and send it as a new e-mail
* through an SMTP server. The e-mail message may contain attachments which
* are the files uploaded from client.
*
* @author www.codejava.net
*
*/
@WebServlet("/SendMailAttachServlet")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class SendMailAttachServlet extends HttpServlet {
private String host;
private String port;
private String user;
private String pass;
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
/**
* handles form submission
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<File> uploadedFiles = saveUploadedFiles(request);
String recipient = request.getParameter("recipient");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
String resultMessage = "";
try {
EmailUtility.sendEmailWithAttachment(host, port, user, pass,
recipient, subject, content, uploadedFiles);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
deleteUploadFiles(uploadedFiles);
request.setAttribute("message", resultMessage);
getServletContext().getRequestDispatcher("/Result.jsp").forward(
request, response);
}
}
/**
* Saves files uploaded from the client and return a list of these files
* which will be attached to the e-mail message.
*/
private List<File> saveUploadedFiles(HttpServletRequest request)
throws IllegalStateException, IOException, ServletException {
List<File> listFiles = new ArrayList<File>();
byte[] buffer = new byte[4096];
int bytesRead = -1;
Collection<Part> multiparts = request.getParts();
if (multiparts.size() > 0) {
for (Part part : request.getParts()) {
// creates a file to be saved
String fileName = extractFileName(part);
if (fileName == null || fileName.equals("")) {
// not attachment part, continue
continue;
}
File saveFile = new File(fileName);
System.out.println("saveFile: " + saveFile.getAbsolutePath());
FileOutputStream outputStream = new FileOutputStream(saveFile);
// saves uploaded file
InputStream inputStream = part.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
listFiles.add(saveFile);
}
}
return listFiles;
}
/**
* Retrieves file name of a upload part from its HTTP header
*/
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length() - 1);
}
}
return null;
}
/**
* Deletes all uploaded files, should be called after the e-mail was sent.
*/
private void deleteUploadFiles(List<File> listFiles) {
if (listFiles != null && listFiles.size() > 0) {
for (File aFile : listFiles) {
aFile.delete();
}
}
}
}
4.) Configure the SMTP server using web.xml
configuration
4.)使用web.xml配置配置SMTP服务器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>EmailAttachWebApp</display-name>
<!-- SMTP settings -->
<context-param>
<param-name>host</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
<context-param>
<param-name>port</param-name>
<param-value>25</param-value>
</context-param>
<context-param>
<param-name>port</param-name>
<param-value>587</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>YOUR_EMAIL</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>YOUR_PASS</param-value>
</context-param>
<welcome-file-list>
<welcome-file>EmailForm.jsp</welcome-file>
</welcome-file-list>
</web-app>
Hope it may help you.!!
希望它可以帮到你。!!
#1
You can do it as:
你可以这样做:
messageBodyPart.setText("This is message body");
messageBodyPart = new MimeBodyPart();
String filename = "/home/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Then send the message using Transport object as:
然后使用Transport对象发送消息:
Transport.send(message);
And, all you need is to update the file path, as you are sending file from client side you can map it directly based on technology servlets/struts2 you were using.
而且,您只需更新文件路径,因为您从客户端发送文件,您可以根据您正在使用的技术servlet / struts2直接映射它。
#2
As you are using the servlet as server side technology then following will be full example to send email with file attachment using servlet.
当您使用servlet作为服务器端技术时,以下将是使用servlet发送带文件附件的电子邮件的完整示例。
1.)Create following Java class with name EmailUtility.java
1.)使用名称EmailUtility.java创建以下Java类
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;
/**
* A utility class for sending e-mail message with attachment.
* @author www.codejava.net
*
*/
public class EmailUtility {
/**
* Sends an e-mail message from a SMTP host with a list of attached files.
*
*/
public static void sendEmailWithAttachment(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message, List<File> attachedFiles)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachedFiles != null && attachedFiles.size() > 0) {
for (File aFile : attachedFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(aFile);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
}
2.) Create following form in your jsp
page
2.)在jsp页面中创建以下表单
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Send an e-mail with attachment</title>
</head>
<body>
<form action="SendMailAttachServlet" method="post" enctype="multipart/form-data">
<table border="0" width="60%" align="center">
<caption><h2>Send New E-mail</h2></caption>
<tr>
<td width="50%">Recipient address </td>
<td><input type="text" name="recipient" size="50"/></td>
</tr>
<tr>
<td>Subject </td>
<td><input type="text" name="subject" size="50"/></td>
</tr>
<tr>
<td>Content </td>
<td><textarea rows="10" cols="39" name="content"></textarea> </td>
</tr>
<tr>
<td>Attach file </td>
<td><input type="file" name="file" size="50" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Send"/></td>
</tr>
</table>
</form>
</body>
</html>
Note that the tag must have attribute enctype="multipart/form-data". If we want to have more attachments we can duplicate the tag.
请注意,标记必须具有enctype =“multipart / form-data”属性。如果我们想要更多附件,我们可以复制标签。
3.) create following servlet class with name SendMailAttachServlet
3.)使用名称SendMailAttachServlet创建以下servlet类
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* A servlet that takes message details from user and send it as a new e-mail
* through an SMTP server. The e-mail message may contain attachments which
* are the files uploaded from client.
*
* @author www.codejava.net
*
*/
@WebServlet("/SendMailAttachServlet")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class SendMailAttachServlet extends HttpServlet {
private String host;
private String port;
private String user;
private String pass;
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
/**
* handles form submission
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<File> uploadedFiles = saveUploadedFiles(request);
String recipient = request.getParameter("recipient");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
String resultMessage = "";
try {
EmailUtility.sendEmailWithAttachment(host, port, user, pass,
recipient, subject, content, uploadedFiles);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
deleteUploadFiles(uploadedFiles);
request.setAttribute("message", resultMessage);
getServletContext().getRequestDispatcher("/Result.jsp").forward(
request, response);
}
}
/**
* Saves files uploaded from the client and return a list of these files
* which will be attached to the e-mail message.
*/
private List<File> saveUploadedFiles(HttpServletRequest request)
throws IllegalStateException, IOException, ServletException {
List<File> listFiles = new ArrayList<File>();
byte[] buffer = new byte[4096];
int bytesRead = -1;
Collection<Part> multiparts = request.getParts();
if (multiparts.size() > 0) {
for (Part part : request.getParts()) {
// creates a file to be saved
String fileName = extractFileName(part);
if (fileName == null || fileName.equals("")) {
// not attachment part, continue
continue;
}
File saveFile = new File(fileName);
System.out.println("saveFile: " + saveFile.getAbsolutePath());
FileOutputStream outputStream = new FileOutputStream(saveFile);
// saves uploaded file
InputStream inputStream = part.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
listFiles.add(saveFile);
}
}
return listFiles;
}
/**
* Retrieves file name of a upload part from its HTTP header
*/
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length() - 1);
}
}
return null;
}
/**
* Deletes all uploaded files, should be called after the e-mail was sent.
*/
private void deleteUploadFiles(List<File> listFiles) {
if (listFiles != null && listFiles.size() > 0) {
for (File aFile : listFiles) {
aFile.delete();
}
}
}
}
4.) Configure the SMTP server using web.xml
configuration
4.)使用web.xml配置配置SMTP服务器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>EmailAttachWebApp</display-name>
<!-- SMTP settings -->
<context-param>
<param-name>host</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
<context-param>
<param-name>port</param-name>
<param-value>25</param-value>
</context-param>
<context-param>
<param-name>port</param-name>
<param-value>587</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>YOUR_EMAIL</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>YOUR_PASS</param-value>
</context-param>
<welcome-file-list>
<welcome-file>EmailForm.jsp</welcome-file>
</welcome-file-list>
</web-app>
Hope it may help you.!!
希望它可以帮到你。!!