- 浏览: 14809 次
- 性别:
- 来自: 苏州
文章分类
最新评论
SendAttanchment.jsp文件--------------------------------测试文件
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'SendAttanchment.jsp' starting page</title>
</head>
<body>
<div align="center">
User JavaMail to send emails:<br>
<form action="servlet/SendAttachment" method="post" ENCTYPE="multipart/form-data">
Recipient: <input type="text" size="40" name="to"><br><br>
Sender: <input type="text" size="40" name="from" value="test@sina.com"><br><br>
Subject:<input type="text" size="40" name="subject" /><br><br>
Attach: <input type="file" name="file" size="28" /><br><br>
Content:<textarea rows="6" cols="38" name="content" />
<input type="submit" value="Send" />
<input type="reset" value="Cancle" />
</form>
</div>
</body>
</html>
AttachmentSender.java
完成邮件的以下一些操作:
1) 设置邮箱名,密码
2) 设置邮件的发送者,接收者,主题,正文,以及附件
3) 实现发送功能
package beans;
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;
public class AttachmentSender {
private MimeMessage message;
private Properties props;
private Session session;
private MimeMultipart mp;
private String name = "";
private String password = "";
/**
* 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 to
*/
public void setTo(String to){
try {
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* set mail subject
* @param subject
*/
public void setSubject(String subject){
try {
message.setSubject(subject);
} 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(String filename){
try{
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(fileds.getName());
mp.addBodyPart(bp);
}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, message.getRecipients(Message.RecipientType.TO));
transport.close();
return true;
}catch(NoSuchProviderException e){
e.printStackTrace();
return false;
}catch (MessagingException e){
e.printStackTrace();
return false;
}
}
}
SendAttachment.java
主要完成以下操作:
1) 解析从JSP传来的参数请求(邮件接收者,发送者,正文,附件)
2) 此处实现添加附件的方法是:先将附件上传至server的工程目录下,然后attach到邮件,然后删除上传到server上的文件
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.Iterator;
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 beans.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.setContentType("text/html");
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.setContentType("text/html");
PrintWriter out = response.getWriter();
//set the smtp address of sina
String host = "smtp.sina.com";
//set mailbox accountName
String accountName = "test";
//set mailbox password
String password = "pass";
//attachment
File uploadedFile = null;
//sender's address
String from = "";
//recipient's address
String to = "";
//mail subject
String subject = "";
//mail content
String content = "";
//upload the attachment to the server first
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator items;
try{
items = upload.parseRequest(request).iterator();
while(items.hasNext()){
FileItem item = (FileItem) items.next();
if(!item.isFormField()){
//get the name of the upload file
String name = item.getName();
String fileName = name.substring(name.lastIndexOf('\\')+1,name.length());
String path = request.getRealPath(fileName);
//upload the file
uploadedFile = new File(path);
item.write(uploadedFile);
}
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();
}
}
//set mail info
AttachmentSender sender = new AttachmentSender(host,accountName,password);
sender.setFrom(from);
sender.setSubject(subject);
sender.setTo(to);
sender.setContent(content);
if(uploadedFile != null){
String attachment = request.getRealPath(uploadedFile.getName());
sender.addAttachMent(attachment);
}
//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())
uploadedFile.delete();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
MyAuthenticator.java
package beans;
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);
}
}
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'SendAttanchment.jsp' starting page</title>
</head>
<body>
<div align="center">
User JavaMail to send emails:<br>
<form action="servlet/SendAttachment" method="post" ENCTYPE="multipart/form-data">
Recipient: <input type="text" size="40" name="to"><br><br>
Sender: <input type="text" size="40" name="from" value="test@sina.com"><br><br>
Subject:<input type="text" size="40" name="subject" /><br><br>
Attach: <input type="file" name="file" size="28" /><br><br>
Content:<textarea rows="6" cols="38" name="content" />
<input type="submit" value="Send" />
<input type="reset" value="Cancle" />
</form>
</div>
</body>
</html>
AttachmentSender.java
完成邮件的以下一些操作:
1) 设置邮箱名,密码
2) 设置邮件的发送者,接收者,主题,正文,以及附件
3) 实现发送功能
package beans;
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;
public class AttachmentSender {
private MimeMessage message;
private Properties props;
private Session session;
private MimeMultipart mp;
private String name = "";
private String password = "";
/**
* 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 to
*/
public void setTo(String to){
try {
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* set mail subject
* @param subject
*/
public void setSubject(String subject){
try {
message.setSubject(subject);
} 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(String filename){
try{
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(fileds.getName());
mp.addBodyPart(bp);
}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, message.getRecipients(Message.RecipientType.TO));
transport.close();
return true;
}catch(NoSuchProviderException e){
e.printStackTrace();
return false;
}catch (MessagingException e){
e.printStackTrace();
return false;
}
}
}
SendAttachment.java
主要完成以下操作:
1) 解析从JSP传来的参数请求(邮件接收者,发送者,正文,附件)
2) 此处实现添加附件的方法是:先将附件上传至server的工程目录下,然后attach到邮件,然后删除上传到server上的文件
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.Iterator;
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 beans.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.setContentType("text/html");
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.setContentType("text/html");
PrintWriter out = response.getWriter();
//set the smtp address of sina
String host = "smtp.sina.com";
//set mailbox accountName
String accountName = "test";
//set mailbox password
String password = "pass";
//attachment
File uploadedFile = null;
//sender's address
String from = "";
//recipient's address
String to = "";
//mail subject
String subject = "";
//mail content
String content = "";
//upload the attachment to the server first
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator items;
try{
items = upload.parseRequest(request).iterator();
while(items.hasNext()){
FileItem item = (FileItem) items.next();
if(!item.isFormField()){
//get the name of the upload file
String name = item.getName();
String fileName = name.substring(name.lastIndexOf('\\')+1,name.length());
String path = request.getRealPath(fileName);
//upload the file
uploadedFile = new File(path);
item.write(uploadedFile);
}
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();
}
}
//set mail info
AttachmentSender sender = new AttachmentSender(host,accountName,password);
sender.setFrom(from);
sender.setSubject(subject);
sender.setTo(to);
sender.setContent(content);
if(uploadedFile != null){
String attachment = request.getRealPath(uploadedFile.getName());
sender.addAttachMent(attachment);
}
//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())
uploadedFile.delete();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
MyAuthenticator.java
package beans;
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);
}
}
相关推荐
在本系统中,JavaMail API利用MIME技术解析和构建带有附件的邮件。 6. 数据存储: 邮箱系统通常需要存储用户信息、邮件内容等数据。可能采用的关系型数据库如MySQL,非关系型数据库如MongoDB,或者云存储服务如...
在这个场景下,我们讨论的是一个使用JSP和Servlet实现的邮件发送系统,该系统具备发送带有多个附件的功能。这个系统可能基于JavaMail API来实现邮件的发送,而JavaMail是一个强大的开源库,可以处理复杂的邮件服务...
无论是HTML格式的富文本邮件,还是带有附件的复杂邮件,或者是简洁的文本邮件,都可以通过JSP和JavaMail API轻松实现。在实际项目中,这些技术可以帮助开发者构建出高效且用户友好的邮件通知系统。
2. **带附件邮件发送**:在电子邮件系统中,发送带有附件的功能是必不可少的。在JSP中,这可以通过MIME(多用途互联网邮件扩展)技术实现。MIME允许在邮件中添加不同类型的数据,如图片、文档或音频文件。开发者需要...
在这个"jsp发送邮件的程序完整版"中,我们将探讨如何使用JSP结合JavaMail API来实现这一功能,特别是处理带有附件的邮件。 首先,要发送邮件,我们需要了解SMTP(Simple Mail Transfer Protocol),这是一个用于...
如果需要发送带有附件的邮件,JavaMail API提供了`Multipart`类,可以将邮件内容和附件一起封装在`MimeMessage`中。 通过以上步骤,你可以利用JSP和JavaMail API开发出一个能够从Web界面发送邮件的应用。在实践中...
6. **附件支持**:支持发送和接收带有附件的邮件,可能需要使用MIME(Multipurpose Internet Mail Extensions)扩展邮件格式。 7. **邮件搜索**:提供搜索功能,让用户可以按关键词查找历史邮件。 **安全性与优化**...
发送带有附件的邮件则需要使用`MimeBodyPart`和`Multipart`类。首先创建`MimeBodyPart`对象来存储附件,然后将其添加到`Multipart`对象中,最后将`Multipart`对象设为`Message`的正文。 接收邮件通常需要连接到POP3...
Spring的邮件支持是通过JavaMailSender接口实现的,它允许开发者轻松地发送各种类型的邮件,包括HTML、文本或者带有附件的邮件。 在本项目中,结合Struts和Spring,我们可以按照以下步骤实现邮件发送: 1. **配置...
- **附件支持**: 允许用户发送和接收带有附件的邮件,可能需要处理不同类型的文件格式。 - **过滤和搜索**: 提供邮件过滤和搜索功能,方便用户查找和管理邮件。 - **通知提醒**: 实现实时的新邮件提醒,可以通过...
JSP网络编程从基础到实践的实例代码 《JSP网络编程从基础到实践》光盘说明 光盘的实例代码目录中包含了前10章的所有实例的源代码,实例名称及其所处章节如下: ... 实例69 发送带有附件的邮件 实例70 接收EMAIL
实现邮件发送功能,可能使用JavaMail API,讲解如何设置SMTP服务器,发送文本或带有附件的邮件。 9. **项目九**:权限管理与登录注册 在这个项目中,可能会涉及用户身份验证和授权,使用session或cookie进行用户...
它提供了一套丰富的API接口,可以用来处理各种类型的邮件,包括但不限于简单的文本邮件、HTML格式邮件以及带有附件的邮件等。虽然JavaMail最初由Sun公司创建,但随着Java技术的发展,JavaMail已经成为了一个开放源...
"基于Java+JSP的邮件管理系统"是一个使用Java编程语言和JSP(JavaServer Pages)技术开发的软件项目,主要用于实现电子邮件的发送、接收和管理功能。这个系统通常会涵盖用户界面、服务器端逻辑以及与邮件服务器的...
例如,用户可以通过填写表单,然后调用JavaMail API发送带有文本、HTML格式或附件的邮件。 具体到邮件系统的实现过程,通常分为以下步骤: 1. **初始化Session**:设置邮件服务器的相关信息,如主机地址、端口号、...
3. **带有附件的邮件**:邮件中可以附加文件,如图片、文档等。 4. **多部分邮件**:结合文本和HTML内容,同时满足不同邮件客户端的显示需求。 5. **使用MIME技术的邮件**:MIME是一种扩展电子邮件标准,允许在邮件...
《JSP网络编程从基础到实践》光盘说明 光盘的实例代码目录中包含了前10章的所有实例的源代码,实例名称及其所处章节如下: 第1章 JSP技术概述 实例1 第一个JSP页面 ... 实例69 发送带有附件的邮件 实例70 接收EMAIL
- 发送邮件:允许用户发送带有附件或纯文本的邮件。 - 收件箱管理:用户可以查看已收到的邮件,并对其进行分类、删除等操作。 - 垃圾邮件过滤:采用一定的算法过滤垃圾邮件,保护用户的邮箱安全。 3. **在线教学...
总之,JSP中的电子邮件功能通过JavaMail API实现,结合`mail.jar`和`activation.jar`库,可以轻松地发送带有或不带附件的邮件。开发者只需要配置正确的邮件服务器参数,并编写相应的代码来创建和发送邮件。这个过程...
通过JavaMail,开发者可以创建、发送带有附件的邮件,处理邮件的接收,甚至进行邮件过滤和管理。 `javamail_jsp`则表明了如何在JSP页面中使用JavaMail。JSP是一种基于Java的服务器端脚本语言,用于生成动态网页内容...