Java实现邮件发送功能
Java实现邮件发送的具体代码,供大家参考,具体内容如下
一、邮件服务器与传输协议
要在网络上实现邮件功能,必须要有专门的邮件服务器。这些邮件服务器类似于现实生活中的邮局,它主要负责接收用户投递过来的邮件,并把邮件投递到邮件接收者的电子邮箱中。
SMTP服务器地址:一般是 smtp.xxx.com,比如163邮箱是smtp.163.com,qq邮箱是smtp.qq.com。
SMTP协议
通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器)。
POP3协议
通常把处理用户pop3请求(邮件接收请求)的服务器称之为POP3服务器(邮件接收服务器)。
二、Java发送邮件
文章图片
使用到的jar包:
- mail.jar
- activation.jar
QQ邮箱–>邮箱设置–>账户–>POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 开启POP3/SMTP服务,然后获取16位授权码(注意不要将授权码泄露,一个账户可以拥有多个授权码)
文章图片
Java实现纯文本邮件发送
package org.westos.email; import com.sun.mail.util.MailSSLSocketFactory; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.security.GeneralSecurityException; import java.util.Properties; public class SendEamil {public static void main(String[] args) throws MessagingException, GeneralSecurityException {//创建一个配置文件并保存Properties properties = new Properties(); properties.setProperty("mail.host","smtp.qq.com"); properties.setProperty("mail.transport.protocol","smtp"); properties.setProperty("mail.smtp.auth","true"); //QQ存在一个特性设置SSL加密MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); //创建一个session对象Session session = Session.getDefaultInstance(properties, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication("619046217@qq.com","16位授权码"); }}); //开启debug模式session.setDebug(true); //获取连接对象Transport transport = session.getTransport(); //连接服务器transport.connect("smtp.qq.com","619046217@qq.com","16位授权码"); //创建邮件对象MimeMessage mimeMessage = new MimeMessage(session); //邮件发送人mimeMessage.setFrom(new InternetAddress("619046217@qq.com")); //邮件接收人mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("875203654@qq.com")); //邮件标题mimeMessage.setSubject("Hello Mail"); //邮件内容mimeMessage.setContent("我的想法是把代码放进一个循环里","text/html; charset=UTF-8"); //发送邮件transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); //关闭连接transport.close(); }}
Java实现文本图片附件复杂的邮件发送
MIME(多用途互联网邮件扩展类型)
MimeBodyPart类
javax.mail.internet.MimeBodyPart类 表示的是一个MIME消息,它和MimeMessage类一样都是从Part接口继承过来。
MimeMultipart类
javax.mail.internet.MimeMultipart是抽象类 Multipart的实现子类,它用来组合多个MIME消息。一个MimeMultipart对象可以包含多个代表MIME消息的MimeBodyPart对象
package org.westos.email; import com.sun.mail.util.MailSSLSocketFactory; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.security.GeneralSecurityException; import java.util.Properties; public class SendComplexEmail {public static void main(String[] args) throws GeneralSecurityException, MessagingException {Properties prop = new Properties(); prop.setProperty("mail.host", "smtp.qq.com"); 设置QQ邮件服务器prop.setProperty("mail.transport.protocol", "smtp"); // 邮件发送协议prop.setProperty("mail.smtp.auth", "true"); // 需要验证用户名密码// QQ邮箱设置SSL加密MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); //1、创建定义整个应用程序所需的环境信息的 Session 对象Session session = Session.getDefaultInstance(prop, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {//传入发件人的姓名和授权码return new PasswordAuthentication("619046217@qq.com","16位授权码"); }}); //2、通过session获取transport对象Transport transport = session.getTransport(); //3、通过transport对象邮箱用户名和授权码连接邮箱服务器transport.connect("smtp.qq.com","619046217@qq.com","16位授权码"); //4、创建邮件,传入session对象MimeMessage mimeMessage = complexEmail(session); //5、发送邮件transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); //6、关闭连接transport.close(); }public static MimeMessage complexEmail(Session session) throws MessagingException {//消息的固定信息MimeMessage mimeMessage = new MimeMessage(session); //发件人mimeMessage.setFrom(new InternetAddress("619046217@qq.com")); //收件人mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("619046217@qq.com")); //邮件标题mimeMessage.setSubject("带图片和附件的邮件"); //邮件内容//准备图片数据MimeBodyPart image = new MimeBodyPart(); DataHandler handler = new DataHandler(new FileDataSource("E:\\IdeaProjects\\WebEmail\\resources\\测试图片.png")); image.setDataHandler(handler); image.setContentID("test.png"); //设置图片id//准备文本MimeBodyPart text = new MimeBodyPart(); text.setContent("这是一段文本","text/html; charset=utf-8"); //附件MimeBodyPart appendix = new MimeBodyPart(); appendix.setDataHandler(new DataHandler(new FileDataSource("E:\\IdeaProjects\\WebEmail\\resources\\测试文件.txt"))); appendix.setFileName("test.txt"); //拼装邮件正文MimeMultipart mimeMultipart = new MimeMultipart(); mimeMultipart.addBodyPart(image); mimeMultipart.addBodyPart(text); mimeMultipart.setSubType("related"); //文本和图片内嵌成功//将拼装好的正文内容设置为主体MimeBodyPart contentText = new MimeBodyPart(); contentText.setContent(mimeMultipart); //拼接附件MimeMultipart allFile = new MimeMultipart(); allFile.addBodyPart(appendix); //附件allFile.addBodyPart(contentText); //正文allFile.setSubType("mixed"); //正文和附件都存在邮件中,所有类型设置为mixed//放到Message消息中mimeMessage.setContent(allFile); mimeMessage.saveChanges(); //保存修改return mimeMessage; }}
JavaWeb发送邮件(网站注册成功发送提示邮件)
1.User
package org.westos.mail; public class User {private String name; private String password; private String mail; public User() {}public User(String name, String password, String mail) {this.name = name; this.password = password; this.mail = mail; }public String getName() {return name; }public void setName(String name) {this.name = name; }public String getPassword() {return password; }public void setPassword(String password) {this.password = password; }public String getMail() {return mail; }public void setMail(String mail) {this.mail = mail; }@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +", password='" + password + '\'' +", mail='" + mail + '\'' +'}'; }}
2.Servlet
package org.westos.mail; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class Servlet extends javax.servlet.http.HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request,response); }protected void doGet(HttpServletRequest request, HttpServletResponse response) {//处理前端请求String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); //将信息封装进user对象User user = new User(username, password, email); SendMail sendMail = new SendMail(user); sendMail.start(); //开启线程request.setAttribute("msg","发送成功"); try {request.getRequestDispatcher("msg.jsp").forward(request,response); } catch (ServletException e) {e.printStackTrace(); } catch (IOException e) {e.printStackTrace(); }}}
3.SengMail
package org.westos.mail; import com.sun.mail.util.MailSSLSocketFactory; import javax.mail.*; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.security.GeneralSecurityException; import java.security.PublicKey; import java.util.Properties; public class SendMail extends Thread {//发件人信息private String From = "619046217@qq.com"; //发件人邮箱private String recipient = "619046217@qq.com"; //邮箱密码private String password = "16位授权码"; //邮件发送的服务器private String host = "smtp.qq.com"; //收件人信息private User user; public SendMail(User user){this.user = user; }@Overridepublic void run() {try {Properties properties = new Properties(); properties.setProperty("mail.host","smtp.qq.com"); properties.setProperty("mail.transport.protocol","smtp"); properties.setProperty("mail.smtp.auth","true"); //QQ存在一个特性设置SSL加密MailSSLSocketFactory sf = null; try {sf = new MailSSLSocketFactory(); } catch (GeneralSecurityException e) {e.printStackTrace(); }sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); //创建一个session对象Session session = Session.getDefaultInstance(properties, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(recipient,password); }}); //开启debug模式session.setDebug(true); //获取连接对象Transport transport = null; try {transport = session.getTransport(); } catch (NoSuchProviderException e) {e.printStackTrace(); }//连接服务器transport.connect(host,From,password); //创建一个邮件发送对象MimeMessage mimeMessage = new MimeMessage(session); //邮件发送人mimeMessage.setFrom(new InternetAddress(recipient)); //邮件接收人mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getMail())); //邮件标题mimeMessage.setSubject("网站注册成功"); //邮件内容mimeMessage.setContent("网站注册成功,密码为"+user.getPassword()+",请妥善保管密码","text/html; charset=UTF-8"); //发送邮件transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); transport.close(); }catch (Exception e){e.printStackTrace(); }}}
4.register.jsp
注册页面 - 锐客网
5.msg.jsp
Title - 锐客网 ${msg}
6.web.xml
Servletorg.westos.mail.ServletServlet /a.do
【Java实现邮件发送功能】以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- MybatisPlus使用queryWrapper如何实现复杂查询
- python学习之|python学习之 实现QQ自动发送消息
- 事件代理
- 孩子不是实现父母欲望的工具——林哈夫
- opencv|opencv C++模板匹配的简单实现
- Java|Java OpenCV图像处理之SIFT角点检测详解
- Node.js中readline模块实现终端输入
- java中如何实现重建二叉树