JavaMail 发送邮件系列(一):发送基本邮件

2024-09-05 11:32

本文主要是介绍JavaMail 发送邮件系列(一):发送基本邮件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用JavaMail API发送邮件,大概分为三个类:MyAuthenticator---密码认证器,MailSendInfo--邮件发送消息集合,MailSendUtils--邮件发送消息注入执行


Maven依赖

<dependency ><groupId > javax.mail </ groupId ><artifactId > mail </ artifactId ><version > 1.4.5 </ version >
</dependency >
<dependency ><groupId > com.sun.mail </ groupId ><artifactId > javax.mail </ artifactId ><version > 1.5.4 </ version >
</dependency >



MyAuthenticator

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;public class MyAuthenticator extends Authenticator {private String userName = null;private String password = null;public MyAuthenticator() {}public MyAuthenticator(String username, String password) {this.userName = username;this.password = password;}protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(userName, password);}
}

MailSendInfo

import java.util.Properties;public class MailSenderInfo {// 发送邮件的服务器的IP和端口private String mailServerHost;private String mailServerPort = "25";// 邮件发送者的地址private String fromAddress;// 登陆邮件发送服务器的用户名和密码private String userName;private String password;// 是否需要身份验证private boolean validate = false;// 邮件主题private String subject;// 邮件的文本内容private String content;// 邮件接收者的地址private String[] toAddress;/*** 获得邮件会话属性*/public Properties getProperties() {Properties p = new Properties();p.put("mail.smtp.host", this.mailServerHost);p.put("mail.smtp.port", this.mailServerPort);p.put("mail.smtp.auth", validate ? "true" : "false");return p;}public String[] getToAddress() {return toAddress;}public void setToAddress(String[] toAddress) {this.toAddress = toAddress;}public String getMailServerHost() {return mailServerHost;}public void setMailServerHost(String mailServerHost) {this.mailServerHost = mailServerHost;}public String getMailServerPort() {return mailServerPort;}public void setMailServerPort(String mailServerPort) {this.mailServerPort = mailServerPort;}public boolean isValidate() {return validate;}public void setValidate(boolean validate) {this.validate = validate;}public String getFromAddress() {return fromAddress;}public void setFromAddress(String fromAddress) {this.fromAddress = fromAddress;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getContent() {return content;}public void setContent(String textContent) {this.content = textContent;}
}

MailSendUtils

import java.util.Date;
import java.util.Properties;import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;public class MailSendUtils {private MailSenderInfo mailInfo = new MailSenderInfo();public MailSendUtils(String subject, String message,String toAddress) {mailInfo.setMailServerHost("smtp.163.com");mailInfo.setMailServerPort("25");mailInfo.setValidate(true);mailInfo.setUserName("lweemooaiz.4r@163.com");mailInfo.setPassword("willsmith228");mailInfo.setFromAddress("lweemooaiz.4r@163.com");mailInfo.setToAddress(new String[]{toAddress});mailInfo.setSubject(subject);mailInfo.setContent(message);}/*** 以TEXT格式发送邮件* */public boolean sendTextMail() {// 判断是否需要身份认证MyAuthenticator authenticator = null;Properties pro = mailInfo.getProperties();if (mailInfo.isValidate()) {// 如果需要身份认证,则创建一个密码验证器authenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());}// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionSession sendMailSession = Session.getDefaultInstance(pro, authenticator);try {// 根据session创建一个邮件消息Message mailMessage = new MimeMessage(sendMailSession);// 创建邮件发送者地址Address from = new InternetAddress(mailInfo.getFromAddress());// 设置邮件消息的发送者mailMessage.setFrom(from);// 创建邮件的接收者地址,并设置到邮件消息中String[] ToAddresses = mailInfo.getToAddress();Address[] addressList = new InternetAddress[ToAddresses.length];for (int i = 0; i < ToAddresses.length; i++) {addressList[i] = new InternetAddress(ToAddresses[i]);}// Message.RecipientType.TO属性表示接收者的类型为TOmailMessage.setRecipients(Message.RecipientType.TO, addressList);// 设置邮件消息的主题mailMessage.setSubject(mailInfo.getSubject());// 设置邮件消息发送的时间mailMessage.setSentDate(new Date());// 设置邮件消息的主要内容String mailContent = mailInfo.getContent();mailMessage.setText(mailContent);// 发送邮件Transport.send(mailMessage);return true;} catch (MessagingException ex) {ex.printStackTrace();}return false;}/*** 以HTML格式发送邮件* */public boolean sendHtmlMail() {// 判断是否需要身份认证MyAuthenticator authenticator = null;Properties pro = mailInfo.getProperties();// 如果需要身份认证,则创建一个密码验证器if (mailInfo.isValidate()) {authenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());}// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionSession sendMailSession = Session.getDefaultInstance(pro, authenticator);try {// 根据session创建一个邮件消息Message mailMessage = new MimeMessage(sendMailSession);// 创建邮件发送者地址Address from = new InternetAddress(mailInfo.getFromAddress());// 设置邮件消息的发送者mailMessage.setFrom(from);// 创建邮件的接收者地址,并设置到邮件消息中String[] ToAddresses = mailInfo.getToAddress();Address[] addressList = new InternetAddress[ToAddresses.length];for (int i = 0; i < ToAddresses.length; i++) {addressList[i] = new InternetAddress(ToAddresses[i]);}// Message.RecipientType.TO属性表示接收者的类型为TOmailMessage.setRecipients(Message.RecipientType.TO, addressList);// 设置邮件消息的主题mailMessage.setSubject(mailInfo.getSubject());// 设置邮件消息发送的时间mailMessage.setSentDate(new Date());// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象Multipart mainPart = new MimeMultipart();// 创建一个包含HTML内容的MimeBodyPartBodyPart html = new MimeBodyPart();// 设置HTML内容html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");mainPart.addBodyPart(html);// 将MiniMultipart对象设置为邮件内容mailMessage.setContent(mainPart);// 发送邮件Transport.send(mailMessage);return true;} catch (MessagingException ex) {ex.printStackTrace();}return false;}
}

MailTest

public class MailTest {public static void main(String[] args) {MailSendUtils sms = new MailSendUtils("this is title", "this is content", "1813110015@qq.com");System.out.println(sms.sendTextMail());}}


pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.cnooc.commons</groupId><artifactId>CPURecordMonitor</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>CPURecordMonitor</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.7</version><scope>test</scope></dependency><dependency ><groupId >javax.mail </groupId ><artifactId >mail </artifactId ><version >1.4.5 </version ></dependency ><dependency ><groupId >com.sun.mail </groupId ><artifactId >javax.mail </artifactId ><version >1.5.4 </version ></dependency ></dependencies ><build ><finalName >CPURecordMonitor </finalName ><plugins ><plugin ><groupId >org.apache.maven.plugins </groupId ><artifactId >maven-compiler-plugin</artifactId ><configuration ><source >1.7 </source ><target >1.7 </target ></configuration ></plugin ></plugins ></build ></project>

中途遇到两个错误

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
java.lang.NoClassDefFoundError: javax/mail/MessagingException
解决方案参考:
http://blog.csdn.net/u013361445/article/details/49663329


Demon下载:http://download.csdn.net/detail/u013361445/9246365

建议下载完毕后自己敲一遍代码,有助于理解。

这篇关于JavaMail 发送邮件系列(一):发送基本邮件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1138833

相关文章

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

python运用requests模拟浏览器发送请求过程

《python运用requests模拟浏览器发送请求过程》模拟浏览器请求可选用requests处理静态内容,selenium应对动态页面,playwright支持高级自动化,设置代理和超时参数,根据需... 目录使用requests库模拟浏览器请求使用selenium自动化浏览器操作使用playwright

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件