JSP 发送邮件

JSP 发送邮件

虽然使用JSP实现邮件发送功能很简单,但是需要有JavaMail API,并且需要安装JavaBean Activation Framework。

下载并解压这些文件,在根目录下,您将会看到一系列jar包。将mail.jar包和activation.jar包加入CLASSPATH变量中。

发送一封简单的邮件

这个例子展示了如何从您的机器发送一封简单的邮件。它假定localhost已经连接至网络并且有能力发送一封邮件。与此同时,请再一次确认mail.jar包和activation.jar包已经添加进CLASSPATH变量中。

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%   
        Properties props = new Properties();
        // 表示SMTP发送邮件,必须进行身份验证
        props.put("mail.smtp.auth", "true");
        //此处填写SMTP服务器
        props.put("mail.smtp.host", "smtp.qq.com");
        //端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587
        props.put("mail.smtp.port", "25");
        // 此处填写你的账号
        props.put("mail.user","1984852655@qq.com");
        // 此处的密码就是前面说的16位STMP口令
        props.put("mail.password","segpcfwwzsuugjjc");

        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息,创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form;
		try {
			form = new InternetAddress(
			        props.getProperty("mail.user"));
		
			message.setFrom(form);
		

        // 设置收件人的邮箱
        InternetAddress to = new InternetAddress("2872718690@qq.com");
        message.setRecipient(Message.RecipientType.TO, to);

        // 设置邮件标题
        message.setSubject("测试邮件");

        // 设置邮件的内容体
        message.setContent("这是一封测试邮件", "text/html;charset=UTF-8");

        // 最后当然就是发送邮件啦
        Transport.send(message);
	} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} %>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<p align="center">
<%     out.println("Result: " + result + "\n"); %>
</p>
</body>
</html>

现在访问http://localhost:8080/SendEmail.jsp,它将会发送一封邮件给abcd@gmail.com 并显示如下结果:

Send Email using JSP
Result: Sent message successfully....

如果想要把邮件发送给多人,下面列出的方法可以用来指明多个邮箱地址:

void addRecipients(Message.RecipientType type, 
                   Address[] addresses)
throws MessagingException

参数的描述如下:

  • type:这个值将会被设置成TO,CC,或BCC。CC代表副本,BCC代表黑色副本,例子程序中使用的是TO。
  • addresses:这是一个邮箱地址的数组,当指定邮箱地址时需要使用InternetAddress()方法。

发送一封HTML邮件

这个例子发送一封简单的HTML邮件。它假定您的localhost已经连接至网络并且有能力发送邮件。与此同时,请再一次确认mail.jar包和activation.jar包已经添加进CLASSPATH变量中。

这个例子和前一个例子非常相似,不过在这个例子中我们使用了setContent()方法,将"text/html"做为第二个参数传给它,用来表明消息中包含了HTML内容。

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%    Properties props = new Properties();
        // 表示SMTP发送邮件,必须进行身份验证
        props.put("mail.smtp.auth", "true");
        //此处填写SMTP服务器
        props.put("mail.smtp.host", "smtp.qq.com");
        //端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587
        props.put("mail.smtp.port", "25");
        // 此处填写你的账号
        props.put("mail.user","1984852655@qq.com");
        // 此处的密码就是前面说的16位STMP口令
        props.put("mail.password","segpcfwwzsuugjjc");

        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息,创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form;
		try {
			form = new InternetAddress(
			        props.getProperty("mail.user"));
		
			message.setFrom(form);
		

        // 设置收件人的邮箱
        InternetAddress to = new InternetAddress("2872718690@qq.com");
        message.setRecipient(Message.RecipientType.TO, to);

        // 设置邮件标题
        message.setSubject("测试邮件");

        // 设置实际的 HTML 消息,内容大小不限
         message.setContent("<h1>This is actual message</h1>",
                            "text/html" );
         // 发送消息
         Transport.send(message);
         String title = "发送电子邮件";
         String res = "成功发送消息...";
         String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " +          "transitional//en\">\n";
         out.println(docType +
         "<html>\n" +
         "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#f0f0f0\">\n" +
         "<h1 align=\"center\">" + title + "</h1>\n" +
         "<p align=\"center\">" + res + "</p>\n" +
         "</body></html>");

        // 最后当然就是发送邮件啦
        Transport.send(message);
	} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
%>
<html>
<head>
<title>Send HTML Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<p align="center">
<%     out.println("Result: " + result + "\n"); %>
</p>
</body>
</html>

现在你可以尝试使用以上JSP文件来发送HTML消息的电子邮件。


在邮件中包含附件

这个例子告诉我们如何发送一封包含附件的邮件。

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%     Properties props = new Properties();
        // 表示SMTP发送邮件,必须进行身份验证
        props.put("mail.smtp.auth", "true");
        //此处填写SMTP服务器
        props.put("mail.smtp.host", "smtp.qq.com");
        //端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587
        props.put("mail.smtp.port", "25");
        // 此处填写你的账号
        props.put("mail.user","1984852655@qq.com");
        // 此处的密码就是前面说的16位STMP口令
        props.put("mail.password","segpcfwwzsuugjjc");

        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息,创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form;
		try {
			form = new InternetAddress(
			        props.getProperty("mail.user"));
		
			message.setFrom(form);
		

        // 设置收件人的邮箱
        InternetAddress to = new InternetAddress("2872718690@qq.com");
        message.setRecipient(Message.RecipientType.TO, to);

        // 设置邮件标题
        message.setSubject("测试邮件");
         // 创建消息部分 
         BodyPart messageBodyPart = new MimeBodyPart();
 
         // 填写消息
         messageBodyPart.setText("This is message body");
         
         // 创建一个多部分消息
         Multipart multipart = new MimeMultipart();
 
         // 设置文本消息部分
         multipart.addBodyPart(messageBodyPart);
 
         // 第二部分是附件
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);
 
         // 发送完整的消息部分
         message.setContent(multipart );
 
         // 发送消息
         Transport.send(message);
         String title = "发送电子邮件";
         String res = "成功发送电子邮件...";
         String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " +          "transitional//en\">\n";
         out.println(docType +
         "<html>\n" +
         "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#f0f0f0\">\n" +
         "<h1 align=\"center\">" + title + "</h1>\n" +
         "<p align=\"center\">" + res + "</p>\n" +
         "</body></html>");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      } %>
<html>
<head>
<title>Send Attachement Email using JSP</title>
</head>
<body>
<center>
<h1>Send Attachement Email using JSP</h1>
</center>
<p align="center">
<%     out.println("Result: " + result + "\n"); %>
</p>
</body>
</html>

用户认证部分

如果邮件服务器需要用户名和密码来进行用户认证的话,可以像下面这样来设置:

 props.setProperty("mail.user", "myuser");
 props.setProperty("mail.password", "mypwd");

使用表单发送邮件

使用HTML表单接收一封邮件,并通过request对象获取所有邮件信息:

String to = request.getParameter("to");
String from = request.getParameter("from");
String subject = request.getParameter("subject");
String messageText = request.getParameter("body");

获取以上信息后,您就可以使用前面提到的例子来发送邮件了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值