How do I atach files in java?
Thank YOU
Thank YOU
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css.css"/>
<title>HRMailer</title>
</head>
<body>
<table width="900">
<tr>
<td valign="top">
<table> <form action="send.jsp" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="120000" />
<tr><td>Subject:</td>
<td><input type="text" name="subject" value=""><td>
</tr>
<tr>
<td>From</td>
<td>
<% //HttpSession session = request.getSession();%>
<input type="text" name="from" value="<%=(String)session.getAttribute("username")%>">
</td> </tr>
<tr>
<td>To:</td>
<td><input type="text" name="to" value=""></td>
</tr>
<tr>
<tr>
<td>Body:</td>
<td valign="buttom">
<textarea rows="10" cols="30" name="body" value="">
</textarea>
</td>
</tr>
<tr>
<td>
attachment
</td>
<td>
<input type="file" name="file" size="30" value="">
</td>
</tr>
<tr>
<td>
<input type="submit" name="send" value="send">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>
Session session = Session.getDefaultInstance(properties);
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(body);
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = mrequest.getParameter("file");
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}
}
catch (MessagingException ex) {
ex.printStackTrace();
}
if(ServletFileUpload.isMultipartContent(request)){
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String file = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + file));
DataSource source = new FileDataSource(UPLOAD_DIRECTORY + File.separator +file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file);
}
}
}
Comment