快捷搜索:  as  2018  FtCWSyGV  С˵  test  xxx  Ψһ  w3viyKQx

亚博im电竞平台:使用Servlet发送电子邮件



应用JavaMail实现收发电子邮件功能一文中先容了若何安装JavaMail,应用JavaMail实现简单的邮件收发功能。本文先容若何应用Servlet发送电子邮件。因为若何应用JavaMail已经在上文中有所先容,是以本文将不做过多的道理先容。

用Servlet实现邮件发送异常简单,我们只是必要构建一个jsp文件,供给给用户提交邮件信息的表单。

Welcome

收件人:

主 题:

内 容:

浏览器网络到用户输入的信息后通报给Servlet来处置惩罚,Servlet经由过程request.getParameter()措施获得相关的数据后,经由过程JavaMail供给的API亚博im电竞平台发送电子邮件。

package com.j2medev.servletmail;

import java.io.IOException;

import java.util.Properties;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.mail.*;

import javax.mail.internet.InternetAddress;

import javax.mail亚博im电竞平台.internet.MimeMessage;

import java.util.*;

import java.net.*;

public class MailServlet extends HttpServlet

{

private static String host;

private static String from;

public void init(ServletConfig config) throws ServletException

{

super.init(config);

host = config.getInitParameter("host");

from = config.getInitParameter("from");

System.out.println(host + from);

}

protected void亚博im电竞平台 doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException

{

doPost(request, response);

}

protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException

{

String send = request.getParameter("send");

String subject = request.getParameter("subject");

String content = request.getParameter("content");

try

{

Properties props = System.getProperties();

// Setup mail server

props.put("mail.smtp.host", host);

// Get session

Session session = Session.getDefaultInstance(props, null);

// Define message

MimeMessage message = new MimeMessage(session);

// Set the from address

message.setFrom(new InternetAddress(from));

// Set the to address

message.addRecipient(Message.RecipientType.TO, new InternetAddress(

send));

// Set the subject

message.setSubject(subject);

// Set the content

message.setText(content);

// Send message

Transport.send(message);

} catch (Exception e)

{

e.printStackTrace();

}

}

}

接下来我们编辑web.xml文件,留意在init-param中写上host和from的参数,以便Servlet初始化的时刻可以读取。

ServletMail

com.j2medev.servletmail.MailServlet

host

smtp.263.net

from

eric.zhan@263.net

ServletMail

/maildo

index.jsp

404

/error.jsp

因为我们必要用到JavaMail和JAF的支持,是以我们必要把相关的包放到Y亚博im电竞平台OURAPP/WEB_INF/lib下。在浏览器输入http://localhost:8080/yourapp/i亚博im电竞平台ndex.jsp 发送电子邮件。

您可能还会对下面的文章感兴趣: