亲宝软件园·资讯

展开

Java邮件发送 Java实现邮件发送的过程及代码详解

Marvellous丶 人气:0

Java实现邮件发送

一、邮件服务器与传输协议

要在网络上实现邮件功能,必须要有专门的邮件服务器。这些邮件服务器类似于现实生活中的邮局,它主要负责接收用户投递过来的邮件,并把邮件投递到邮件接收者的电子邮箱中。

SMTP服务器地址:一般是 smtp.xxx.com,比如163邮箱是smtp.163.com,qq邮箱是smtp.qq.com。

SMTP协议
通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器)。

POP3协议
通常把处理用户pop3请求(邮件接收请求)的服务器称之为POP3服务器(邮件接收服务器)。

二、Java发送邮件

使用到的jar包:

QQ邮箱需获取相应的权限:

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() {
   @Override
   protected 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() {
   @Override
   protected 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("这是一段文本<img src='cid:test.png'>","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;
 }

 @Override
 public 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;
 }

 @Override
 public 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() {
    @Override
    protected 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

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>注册页面</title>
</head>
<body>

<form action="${pageContext.request.contextPath}/a.do" method="post">
 <p>用户名:<input type="text" name="username" required></p>
 <p>密码:<input type="password" name="password" required></p>
 <p>邮箱:<input type="email" name="email" required></p>
 <p><input type="submit" value="提交"></p>
</form>
</body>
</html>

5.msg.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

6.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
   version="4.0">
 <servlet>
  <servlet-name>Servlet</servlet-name>
  <servlet-class>org.westos.mail.Servlet</servlet-class>
 </servlet>

 <servlet-mapping>
  <servlet-name>Servlet</servlet-name>
  <url-pattern>/a.do</url-pattern>
 </servlet-mapping>
</web-app>

到此这篇关于Java实现邮件发送的过程及代码详解的文章就介绍到这了,更多相关Java实现邮件发送内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

加载全部内容

相关教程
猜你喜欢
用户评论