Java 发送邮件
1.java泛型2.Java面向对象三大特征3.Java设计模式——策略模式4.Java设计模式——代理模式5.Java设计模式——装饰者模式6.Java设计模式——单例模式+工厂模式7.Java 定时任务quartz8.java 基本操作9.JavaWeb获取信息10.Java操作Html11.java 定时任务12.Java 读取文件
13.Java 发送邮件
14.Java解析JSON数据15.java线程之CompletableFuture16.java8 新特性之日期时间 API17.java8 新特性之Optional 类18.java8 新特性之默认方法19.java8 新特性之方法引用20.java8 新特性之Lambda 表达式21.java8 新特性之函数式接口22.Java操作Zip23.Java集成验证码一、java发送Email需要引入email jar包,依赖如下:
<!-- https://mvnrepository.com/artifact/javax.mail/mail --> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
二、代码如下,使用139邮箱发送:
// 收件人电子邮箱 // String to = "*********@163.com"; String to = "*********@qq.com"; // 发件人电子邮箱 String from = "*********@139.com"; // 指定发送邮件的主机为 smtp.qq.com String host = "smtp.139.com"; //139 邮件服务器 // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.auth", "true"); // 获取默认session对象 Session session = Session.getDefaultInstance(properties,new Authenticator(){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, "********"); //发件人邮件用户名、密码 } }); try{ // 创建默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // Set From: 头部头字段 message.setFrom(new InternetAddress(from)); // Set To: 头部头字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: 头部头字段 message.setSubject("邮件头部!"); // 设置消息体 message.setContent("测试", "text/html;charset=utf-8"); // 设置内容 如果我们所使用的MimeMessage中信息内容是文本的话,我们便可以直接使用setText()方法来方便的设置文本内容 message.setContent("<h2 style=\"color: red\">Hello World!</h2>\n", "text/html;charset=utf-8"); // 发送消息 Transport.send(message); System.out.println("发送 信息 成功...."); }catch (MessagingException e) { e.printStackTrace(); }
三、如果是QQ邮件的话,需要引入另一个包 进行加密 不加密也可以发送
加密的话需要引入另一个包
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail --> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.1</version> </dependency>
// 收件人电子邮箱 // String to = "*******@163.com"; String to = "*******@qq.com"; // 发件人电子邮箱 String from = "*******@qq.com"; // 指定发送邮件的主机为 smtp.qq.com String host = "smtp.qq.com"; //QQ 邮件服务器 // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.auth", "true"); // 下面四行不加也可以发送 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(){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from , "*******"); //发件人邮件用户名、密码 } }); try{ // 创建默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // Set From: 头部头字段 message.setFrom(new InternetAddress(from)); // Set To: 头部头字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: 头部头字段 message.setSubject("邮件标题"); // 设置消息体 message.setContent("测试", "text/html;charset=utf-8"); // 设置内容 如果我们所使用的MimeMessage中信息内容是文本的话,我们便可以直接使用setText()方法来方便的设置文本内容 message.setText("This is actual message"); // 发送消息 Transport.send(message); System.out.println("发送成功...."); }catch (MessagingException e) { e.printStackTrace(); }
四、发送163邮件
public static void send163Mail(String toMail,String fromMail,String pwd,String content,String title) throws Exception{ Properties prop = new Properties(); prop.setProperty("mail.host", host_163); //// 设置163邮件服务器 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); //使用JavaMail发送邮件的5个步骤 //创建定义整个应用程序所需的环境信息的 Session 对象 Session session = Session.getDefaultInstance(prop, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { //发件人邮件用户名、授权码 return new PasswordAuthentication(fromMail, pwd); } }); try{ // 创建默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // Set From: 头部头字段 message.setFrom(new InternetAddress(fromMail)); // Set To: 头部头字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail)); // Set Subject: 头部头字段 message.setSubject(title); // 设置消息体 message.setContent("测试", "text/html;charset=utf-8"); // 设置内容 如果我们所使用的MimeMessage中信息内容是文本的话,我们便可以直接使用setText()方法来方便的设置文本内容 message.setContent("<h2 style=\"color: red\">"+content+"</h2>\n", "text/html;charset=utf-8"); // 发送消息 Transport.send(message); System.out.println("发送 信息 成功...."); }catch (MessagingException e) { e.printStackTrace(); }
四、发送邮件并携带附件,邮件内容html格式,代码如下:
package com.mmall.util; import com.sun.mail.util.MailSSLSocketFactory; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.*; public class SendMailFile { // MIME邮件对象 private static MimeMessage mimeMsg; // 邮件会话对象 private static Session session; // 系统属性 private static Properties properties= System.getProperties();; // Multilpart对象,邮件内容,标题,附件等内容均添加到其中后再生成 private static Multipart mp; // 发件人用户名 private static String username="251231466@qq.com"; // 发件人密码 private static String password="whgodxpzprb"; // 发件人昵称 private static String nickname="wanghao"; // 收件人 private static String sendName="ssrs_wanghao@163.com"; // smtp private static String smtp="smtp.qq.com"; public static void main(String[] args) { //设置邮件发送的SMTP主机 properties.put("mail.smtp.host", smtp); properties.put("mail.smtp.auth", "true"); if(smtp!=null && smtp.indexOf("qq")>0){ // 下面四行不加也可以发送 QQ邮箱设置 System.out.println("进入setQQ 加密"); MailSSLSocketFactory sf = null; try { sf = new MailSSLSocketFactory(); } catch (GeneralSecurityException e) { e.printStackTrace(); } assert sf != null; sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); } // 获取邮件会话对象 session = Session.getDefaultInstance(properties,new Authenticator(){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); //发件人邮件用户名、密码 } }); // 创建邮件MIME对象 mimeMsg = new MimeMessage(session); mp = new MimeMultipart(); try { nickname = MimeUtility.encodeText(nickname, "utf-8", "B"); mimeMsg.setFrom(new InternetAddress(nickname + "<" + username + ">")); // 将收件人数组设置为InternetAddress数组类型 String [] receivers= new String[] {sendName}; List<InternetAddress> receiverList = new ArrayList<InternetAddress>(); for (String receiver : receivers) { receiverList.add(new InternetAddress(receiver)); } InternetAddress[] addresses = receiverList.toArray(new InternetAddress[receivers.length]); mimeMsg.setRecipients(Message.RecipientType.TO, addresses); // 将抄送人数组设置为InternetAddress数组类型 String [] copyTos = new String[0]; List<InternetAddress> copyToList = new ArrayList<InternetAddress>(); for (String copyto : copyTos) { copyToList.add(new InternetAddress(copyto)); } InternetAddress[] copyAddresses = copyToList.toArray(new InternetAddress[copyTos.length]); mimeMsg.setRecipients(Message.RecipientType.CC, copyAddresses); Map<String,String> map = new HashMap<>(); map.put("file1","C:/Users/Administrator/Desktop/teset.txt"); map.put("file2","C:/Users/Administrator/Desktop/teset - 副本.txt"); setFileAffix(map); mimeMsg.setSubject(MimeUtility.encodeText("主题:测试发送邮件带文件", "utf-8", "B")); // 内容 BodyPart bp = new MimeBodyPart(); bp.setContent("" + "<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "<head>\n" + " <meta charset=\"UTF-8\">\n" + " <title>Title</title>\n" + " <script type=\"text/javascript\">\n" + " function f() {\n" + " alert('你点击了');\n" + " }\n" + " </script>\n" + "</head>\n" + "<body>\n" + " <h1 style=\"color: red\" onclick=\"f()\">这是一封测试发送邮件带附件的邮件</h1>\n" + "<p style=\"color: #000bff;\">不用回复,我就看下css样式</p>\n" + "<input type=\"button\" onclick=\"f()\" value=\"我是一个按钮\"/>\n" + "</body>\n" + "</html>\n", "text/html;charset=utf-8"); mp.addBodyPart(bp); mimeMsg.setContent(mp); mimeMsg.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect((String) properties.get("mail.smtp.host"), username, password); transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO)); transport.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } }/** * 添加邮件附件,附件可为多个 * @param fileMap 文件绝对路径map集合 * @throws MessagingException */ public static void setFileAffix(Map<String, String> fileMap) throws MessagingException, UnsupportedEncodingException { // 获取附件 for (String file: fileMap.keySet()) { // 创建一个存放附件的BodyPart对象 BodyPart bp = new MimeBodyPart(); // 获取文件路径 String filePath = fileMap.get(file); String[] fileNames = filePath.split("/"); // 获取文件名 String fileName = fileNames[fileNames.length-1]; // 设置附件名称,附件名称为中文时先用utf-8编码 bp.setFileName(MimeUtility.encodeWord(fileName, "utf-8", null)); FileDataSource fields = new FileDataSource(filePath); bp.setDataHandler(new DataHandler(fields)); // multipart中添加bodypart mp.addBodyPart(bp); } } }
其它:
文章参考:
https://blog.csdn.net/Cindypin/article/details/79026910
邮件api介绍:
https://blog.csdn.net/imain/article/details/1453677
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类