javamail 发送邮件 jsp/servlet

非纯原创 在其他代码上修改而来 可实现发送多个附件 可给多个人发送 用,分割

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);  
    }  
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
以下是使用JavaMail API以外的方式在servlet发送邮件的示例代码: ```java import javax.mail.*; import javax.mail.internet.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class EmailServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置收件人 String to = "[email protected]"; // 设置发件人 String from = "[email protected]"; // 设置SMTP服务器地址 String host = "smtp.example.com"; // 创建邮件会话 Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); // 创建邮件消息 try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置邮件主题 message.setSubject("Test Email"); // 设置邮件正文 message.setText("This is a test email."); // 发送邮件 Transport.send(message); String result = "Email sent successfully."; request.setAttribute("result", result); } catch (MessagingException mex) { mex.printStackTrace(); String result = "Error: " + mex.getMessage(); request.setAttribute("result", result); } // 转发到结果页面 RequestDispatcher dispatcher = request.getRequestDispatcher("result.jsp"); dispatcher.forward(request, response); } } ``` 在上面的代码中,我们使用`javax.mail`和`javax.mail.internet`包中的类来创建邮件消息并发送邮件。我们首先设置了收件人、发件人和SMTP服务器地址。然后,我们创建了一个邮件会话,并使用`MimeMessage`类创建了邮件消息。我们设置了邮件主题和正文,并使用`Transport`类的`send()`方法发送邮件。最后,我们将结果存储在请求对象中,并将请求转发到结果页面。 请注意,此示例仅用于演示目的。在实际应用程序中,您可能需要更复杂的逻辑来处理邮件发送失败、验证输入等方面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值