Servlet 发送电子邮件
Servlet 发送电子邮件
使用 Servlet 发送一封电子邮件是很简单的,但首先您必须在您的计算机上安装 JavaMail API 和 Java Activation Framework)JAF)。
- 您可以从 Java 标准网站下载最新版本的 JavaMail(版本 1.2)。
- 您可以从 Java 标准网站下载最新版本的 JAF(版本 1.1.1)。
下载并解压缩这些文件,在新创建的顶层目录中,您会发现这两个应用程序的一些 jar 文件。您需要把 mail.jar 和 activation.jar 文件添加到您的 CLASSPATH 中。
发送一封简单的电子邮件
下面的实例将从您的计算机上发送一封简单的电子邮件。这里假设您的本地主机已连接到互联网,并支持发送电子邮件。同时确保 Java Email API 包和 JAF 包的所有的 jar 文件在 CLASSPATH 中都是可用的。
package com;import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;/*** Servlet implementation class SendEmail*/
@WebServlet("/SendEmail")
public class SendEmail extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public SendEmail() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubProperties props = new Properties();// 表示SMTP发送邮件,必须进行身份验证props.put("mail.smtp.auth", "true");//此处填写SMTP服务器props.put("mail.smtp.host", "smtp.qq.com");//端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587props.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 blocke.printStackTrace();}catch (MessagingException e) {// TODO Auto-generated catch blocke.printStackTrace();} }/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}
现在让我们来编译上面的 Servlet,并在 web.xml 文件中创建以下条目:
....<servlet><servlet-name>SendEmail</servlet-name><servlet-class>SendEmail</servlet-class></servlet><servlet-mapping><servlet-name>SendEmail</servlet-name><url-pattern>/SendEmail</url-pattern></servlet-mapping>
....
现在通过访问 URL http://localhost:8080/SendEmail 来调用这个 Servlet。这将会发送一封电子邮件到给定的电子邮件 ID abcd@gmail.com,并将显示下面所示的响应:
发送电子邮件成功发送消息... |
如果您想要发送一封电子邮件给多个收件人,那么请使用下面的方法来指定多个电子邮件 ID:
void addRecipients(Message.RecipientType type, Address[] addresses)
throws MessagingException
下面是对参数的描述:
- type:这将被设置为 TO、CC 或 BCC。在这里,CC 代表抄送,BCC 代表密件抄送。例如 Message.RecipientType.TO。
- addresses:这是电子邮件 ID 的数组。当指定电子邮件 ID 时,您需要使用 InternetAddress() 方法。
发送一封 HTML 电子邮件
下面的实例将从您的计算机上发送一封 HTML 格式的电子邮件。这里假设您的本地主机已连接到互联网,并支持发送电子邮件。同时确保 Java Email API 包和 JAF 包的所有的 jar 文件在 CLASSPATH 中都是可用的。
本实例与上一个实例很类似,但是这里我们使用 setContent() 方法来设置第二个参数为 "text/html" 的内容,该参数用来指定 HTML 内容是包含在消息中的。
使用这个实例,您可以发送内容大小不限的 HTML 内容。
package com;import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;/*** Servlet implementation class SendEmail*/
@WebServlet("/SendEmail")
public class SendEmail extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public SendEmail() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubProperties props = new Properties();// 表示SMTP发送邮件,必须进行身份验证props.put("mail.smtp.auth", "true");//此处填写SMTP服务器props.put("mail.smtp.host", "smtp.qq.com");//端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587props.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 blocke.printStackTrace();}catch (MessagingException e) {// TODO Auto-generated catch blocke.printStackTrace();} }/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}
编译并运行上面的 Servlet ,在给定的电子邮件 ID 上发送 HTML 消息。
在电子邮件中发送附件
下面的实例将从您的计算机上发送一封带有附件的电子邮件。这里假设您的本地主机已连接到互联网,并支持发送电子邮件。同时确保 Java Email API 包和 JAF 包的所有的 jar 文件在 CLASSPATH 中都是可用的。
package com;import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;/*** Servlet implementation class SendEmail*/
@WebServlet("/SendEmail")
public class SendEmail extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public SendEmail() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubProperties props = new Properties();// 表示SMTP发送邮件,必须进行身份验证props.put("mail.smtp.auth", "true");//此处填写SMTP服务器props.put("mail.smtp.host", "smtp.qq.com");//端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587props.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();}}
}
编译并运行上面的 Servlet ,在给定的电子邮件 ID 上发送带有文件附件的消息。
用户身份认证部分
如果需要向电子邮件服务器提供用户 ID 和密码进行身份认证,那么您可以设置如下属性:
props.setProperty("mail.user", "myuser");props.setProperty("mail.password", "mypwd");
电子邮件发送机制的其余部分与上面讲解的保持一致。
身份验证
- 要把qq的smtp服务打开!!!如果用qq邮箱服务器的话,记住验证码,在写代码的时候密码是这个验证码!!!
- DataSource
由于javamail 的包里默认的对javax.activation.datasource只有两个实现:
分别是:filedatasource和urldatasource。
因此在webapp里为了不把上传的文件再保存为本地文件,然后再使用filedatasource,
- DataHandler
- 所以该接口只有一个函数,该函数提供了将原始数据格式转为业务所需数据格式,框架提供了常用接口处理器实现,若以下的处理器无法满足需求可以自己实现一个处理器。
Servlet 发送电子邮件相关推荐
- Java发送电子邮件(使用mail.jar和activation.jar)
本文参考使用技术Java+JSP+Servlet 本次源代码可在本人网盘下载:http://pan.baidu.com/s/1jIdV7r4 循序渐进介绍如何使用Java发送电子邮件 一.J2EE+前 ...
- SpringBoot整合:Druid、MyBatis、MyBatis-Plus、多数据源、knife4j、日志、Redis,Redis的Java操作工具类、封装发送电子邮件等等
SpringBoot笔记 一.SpringBoot 介绍 1.1.SpringBoot简介 SpringBoot 是一个快速开发的框架, 封装了Maven常用依赖.能够快速的整合第三方框架:简化XML ...
- 亚马逊ses如何发qq_使用Amazon SES发送电子邮件
亚马逊ses如何发qq by Kangze Huang 黄康泽 使用Amazon SES发送电子邮件 (Sending emails with Amazon SES) 完整的AWS Web样板-教程3 ...
- php mail函数_PHP发送电子邮件函数mail详解
重要:本文最后更新于2019-10-09 08:49:07,某些文章具有时效性,若有错误或已失效,请在下方留言或联系代码狗. PHP作为一门使用广泛的脚本语言,经过这么多年发展已经非常完善了,发送电子 ...
- 如何使用PHP发送电子邮件?
本文翻译自:How to send an email using PHP? I am using PHP on a website and I want to add emailing functio ...
- 如何从我的Android应用程序发送电子邮件?
我正在为Android编写应用程序. 如何从中发送电子邮件? #1楼 简单尝试这个 public void onCreate(Bundle savedInstanceState) {super.onC ...
- 在Python中使用SMTP发送电子邮件
Python中有内置的smtplib模块,完成一封邮件的发送,需要做很多准备工作.第三方的py_smtp这个包也是基于smtplib的,在Python中使用py_smtp发送电子邮件非常方便,只要填写 ...
- C# 发送电子邮件(含附件)用到的类 system.web.mail
主要是用到了System.Web.Mail命名空间,用到了此空间的三个类,分别是: ●MailMessage类,用于构造电子邮件 ●MailAttachment类,用于构造电子邮件附件 ●SmtpMa ...
- net类库中发送电子邮件的方法总结
发送电子邮件是许多需要用户注册的网站的通用功能,通过正则表达式我们可以过滤掉不符合电子邮件格式的输入,但是仍没有办法确保用户填写的电子邮件地址一定是他本人真实有效的电子邮件地址,通常验证电子邮件真实有 ...
最新文章
- ansible 详解
- LINUX应用修改硬件寄存器l,郝健: Linux内存管理学习笔记-第2节课【转】
- vs2010发布、打包安装程序(超全超详细)
- Redis-学习笔记04【Jedis代码操作】
- Java Annotation详解
- 随机加解密java_JAVA随机数生成 Math.random和java.util.Random使用简介
- 如何在Java 8中使用filter()方法
- 计算机的好处和坏处的英语作文,电脑的利弊英语作文
- pandas to_sql保存数据到数据库后,添加自增长的主键ID(PRIMARY KEY)
- GDB调试汇编堆栈过程的学习
- 是否,是否,总是富肥穷瘦?(文末上周投票公布)
- python把utf8编码转为gbk_Python:UTF-8编码转换成GBK编码
- 解决Mac无法识别移动硬盘以及无法识别BootCamp Windows分区的问题
- AutoUpdater 实现一个简易的自动升级工具
- 从turtlesim到贪吃蛇……(补充)
- 网络新文化现象:newbilitynbsp;(不代表…
- 给ibus-rime输入法添加小鹤双拼方案
- 百度地图自定义图标偏移问题
- 公关世界杂志公关世界杂志社公关世界编辑部2022年第22期目录
- 我只说一次,这样用领英开发国外客户,屡试不爽!
热门文章
- 关于Trunk、Hybrid、Access、Tag、Untag、Pvid的关系
- git push origin HEAD:refs/for/master解析
- Supervisor 进程管理
- 为什么说算法不是人工智能的核心
- CocosCreator微信小游戏排行榜及开放数据域的理解与使用
- 一字一句的搞懂vue-cli之vue webpack template配置
- 谈判技巧---From一亩三分地帖子
- box-sizing:border-box的作用
- Element-UI组件之表单Form
- SAP GOS附件上传与下载[代码直接可用]