• JavaWeb之邮件发送


    1.JavaMail组件

    JavaMail下载:http://www.oracle.com/technetwork/java/javamail/index-138643.html?ssSourceSiteId=ocomen

    核心的类和接口:

    javax.mail.Session
    javax.mail.Message
    javax.mail.Address
    javax.mail.Authenticator
    javax.mail.Transport
    javax.mail.Store
    javax.mail.Folder

    2.简单代码实例

    前提是电脑安装了邮件客户端

    package com.v512;
    
    import java.util.Properties;
    
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    public class SendMail {
    
        public static void main(String[] args) {
            
            Properties props =new Properties();
            Session session =Session.getInstance(props,null);
            props.put("mail.host", "127.0.0.1");
            props.put("mail.transport.protocol", "smtp");
            
            Message message = new MimeMessage(session);
            try {
                message.setFrom(new InternetAddress("liuwei8809@163.com"));
                message.setRecipient(Message.RecipientType.TO, new InternetAddress("zhangliguo_china@sina.com"));
                message.setSubject("你好吗?");
                message.setText("JavaMail发送邮件测试。");
                Transport.send(message);
            } catch (AddressException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
    
        }
    
    }

    3.使用其他的邮件服务器

    大型的网站一般都会提供邮件服务器,例如新浪,搜狐,网易等等

    使用Apache Commons 中的 Email组件,下载地址:http://commons.apache.org/email/download_email.cgi

    使用这个组件可以比较轻松地实现邮件的发送

    4.带附件的邮件发送实例

    步骤一:编写页面

    发送邮件页面:sendAttachmentMail.jsp

    <%@ page pageEncoding="UTF-8" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>发送邮件</title>
    </head>
    
    <body>
    <p align="center">发送邮件的程序</p>
    <form id="form1" name="form1" method="post" action="<%=request.getContextPath()%>/servlet/sendAttachmentMail" 
      enctype="multipart/form-data">
      <table width="516" height="253" border="0" align="center">
        <tr>
          <td>收件人:</td>
          <td><label>
            <input type="text" name="to" id="to" />
          </label></td>
        </tr>
        <tr>
          <td>发件人:</td>
          <td><label>
            <input type="text" name="from" id="from" />
          </label></td>
        </tr>
        <tr>
          <td>主题:</td>
          <td><label>
            <input type="text" name="subject" id="subject" />
          </label></td>
        </tr>
        <tr>
          <td>选择附件:</td>
          <td><label>
            <input type="file" name="attachment" id="file" />
          </label></td>
        </tr>
        <tr>
          <td>内容:</td>
          <td><label>
            <textarea name="content" id="content" cols="45" rows="8"></textarea>
          </label></td>
        </tr>
        <tr>
          <td><label>
            <input type="submit" name="button" id="button" value="提交" />
          </label></td>
          <td><label>
            <input type="reset" name="button2" id="button2" value="重置" />
          </label></td>
        </tr>
      </table>
    </form>
    <p align="center">&nbsp;</p>
    <p>&nbsp; </p>
    </body>
    
    </html>

    显示发送结果的页面:

    <%@ page language="java"  pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
           
        <title>display upload result</title>
    
      </head>
      
      <body> 
        <center>
        <p> ${requestScope['sendmail.message'] }</p>
        </center>
      </body>
    </html>

    步骤二:邮件发送的处理:sendAttachmentMailServlet

    package com.v512;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.mail.EmailAttachment;
    import org.apache.commons.mail.EmailException;
    import org.apache.commons.mail.MultiPartEmail;
    
    public class SendAttachmentMailServlet extends HttpServlet {
    
        private static final long serialVersionUID = -1408700020471642036L;
        private ServletContext sc;
        private String savePath;
        private Map<String, String> parameters = new HashMap<String, String>();
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response);
    
        }
        
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            File file = this.doAttachment(request);
    
            MultiPartEmail email = new MultiPartEmail();
            email.setCharset("UTF-8");
            

    email.setHostName("smtp.sina.com"); email.setAuthentication("web08", "web2008"); //特别注意这里!!!!设置邮件服务器和身份的验证

            try {
                email.addTo(parameters.get("to"));
                email.setFrom(parameters.get("from"));
                email.setSubject(parameters.get("subject"));
                email.setMsg(parameters.get("content"));
                if (file != null) {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(file.getPath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setName(file.getName());
                    email.attach(attachment);
                }
                email.send();
                request.setAttribute("sendmail.message", "邮件发送成功!");
            } catch (EmailException e) {
                e.printStackTrace();
                request.setAttribute("sendmail.message", "邮件发送不成功!");
            }
    
            request.getRequestDispatcher("/sendResult.jsp").forward(request,
                    response);
    
        }
    
        public File doAttachment(HttpServletRequest request)
                throws ServletException, IOException {
            File file = null;
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
    
            try {
                List items = upload.parseRequest(request);
                Iterator it = items.iterator();
                while (it.hasNext()) {
                    FileItem item = (FileItem) it.next();
                    if (item.isFormField()) {
                        parameters
                                .put(item.getFieldName(), item.getString("UTF-8"));
                    } else {
                        if (item.getName() != null && !item.getName().equals("")) {
                            File tempFile = new File(item.getName());
                            file = new File(sc.getRealPath("/") + savePath,
                                    tempFile.getName());
                            item.write(file);
    
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("upload.message", "上传文件不成功!");
            }
            return file;
        }
    
        public void init(ServletConfig config) {
            savePath = config.getInitParameter("savePath");
            sc = config.getServletContext();
        }
    
    }

    步骤三:修改web.xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <servlet>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class>com.v512.UploadServlet</servlet-class>
        <init-param>
        <param-name>savePath</param-name>
        <param-value>uploads</param-value>
        </init-param>
      </servlet>
      <servlet>
        <servlet-name>SendMailServlet</servlet-name>
        <servlet-class>com.v512.SendMailServlet</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>SendAttachmentMailServlet</servlet-name>
        <servlet-class>com.v512.SendAttachmentMailServlet</servlet-class>
        <init-param>
        <param-name>savePath</param-name>
        <param-value>uploads</param-value>
        </init-param>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/servlet/upload</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>SendMailServlet</servlet-name>
        <url-pattern>/servlet/sendMail</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>SendAttachmentMailServlet</servlet-name>
        <url-pattern>/servlet/sendAttachmentMail</url-pattern>
      </servlet-mapping>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

    至此,可以添加附件的邮件发送程序就OK啦!

  • 相关阅读:
    shell之for和if实现批量替换多目录下的文件
    问题:Linux报swap空间占用过高,但物理内存还有空余
    git常用命令汇总
    VMware下liunx虚拟机仅主机模式上网
    通过Navicat for MySQL远程连接的时候报错mysql 1130的解决方法
    Linux启动过程简述
    Nginx禁止ip访问或IP网段访问方法
    解决docker主机配置了DaoCloud.io的加速后重启失败问题Failed to start Docker Application Container Engine
    Windows下用python来获取微信撤回消息
    Oracle 参数文件spfile
  • 原文地址:https://www.cnblogs.com/yinger/p/2173867.html
Copyright © 2020-2023  润新知