Java中邮箱的相关使用

  • 1 Java中邮箱的简介
  • 2 邮箱的使用
    • 1 Java原生操作邮箱
      • 1 导入maven坐标
      • 2 添加邮件工具类
    • 2 SpringBoot中操作邮箱
      • 0 准备一个好的SpringBoot环境
      • 1 添加maven坐标
      • 2 添加发送邮箱接口
      • 3 添加发送邮箱实现类
      • 4 添加配置文件
      • 5 添加一个控制器
      • 6 测试
  • 3 错误问题
    • 1 smtp.SMTPSendFailedException: 553 Mail from must equal authorized user

项目中常常有一些场景需要发送邮箱, 整理一下使用邮箱的相关实现

1 Java中邮箱的简介

电子邮件在网络中传输和网页一样需要遵从特定的协议,常用的电子邮件协议包括 SMTP,POP3,IMAP。其中邮件的创建和发送只需要用到 SMTP协议( Simple Mail Transfer Protocol) ,即简单邮件传输协议。

2 邮箱的使用

1 Java原生操作邮箱

1 导入maven坐标

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

2 添加邮件工具类

public class MailTest {// 发邮件账号public static String sendEmailAccount = "Xxx@163.com";// 发邮箱账号授权码public static String sendEmailPassword = "****";// 发邮箱账号主机public static String sendEmailSMTPHost = "smtp.163.com";// 发邮箱协议public static String sendEmailProtocol = "smtp";// 邮件的标题public static String sendEmailSubject = "邮件的标题";// 邮件的内容public static String sendEmailContext = "邮件的内容";// 收邮箱账号public static String receiveMailAccount = "Xxx@qq.com";public static void main(String[] args) {// 配置参数Properties prop = new Properties();// 发件人的邮箱的SMTP 服务器地址(不同的邮箱,服务器地址不同,如139和qq的邮箱服务器地址不同)prop.setProperty("mail.host", sendEmailSMTPHost);// 使用的协议(JavaMail规范要求)prop.setProperty("mail.transport.protocol", sendEmailProtocol);// 需要请求认证prop.setProperty("mail.smtp.auth", "true");// 使用JavaMail发送邮件的5个步骤// 1 创建sessionSession session = Session.getInstance(prop);// 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态session.setDebug(true);Transport ts = null;try {// 2 通过session得到transport对象ts = session.getTransport();// 3 使用账户和授权码ts.connect(sendEmailSMTPHost, sendEmailAccount, sendEmailPassword);// 4 创建邮件Message message = createSimpleMail(session);// 5 发送邮件ts.sendMessage(message, message.getAllRecipients());} catch (NoSuchProviderException e) {e.printStackTrace();} catch (MessagingException e) {e.printStackTrace();} finally {try {// 关闭transport对象ts.close();} catch (MessagingException e) {e.printStackTrace();}}}/*** 创建只包含文本的邮件** @param session* @return* @throws MessagingException*/public static MimeMessage createSimpleMail(Session session)throws MessagingException {// 创建邮件对象MimeMessage message = new MimeMessage(session);// 指明发件人message.setFrom(new InternetAddress(sendEmailAccount));// 指明收件人message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiveMailAccount));// 可选 添加收件人
//        message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiveMailAccount));//    Cc: 抄送(可选)
//        message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(receiveMailAccount));//    Bcc: 密送(可选)
//        message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(receiveMailAccount));// 邮件的标题message.setSubject(sendEmailSubject,"UTF-8");// 邮件的文本内容message.setContent(sendEmailContext, "text/html;charset=UTF-8");// 设置显示发件时间message.setSentDate(new Date());return message;}/*** 创建包含文本和附件的邮件** @param session* @return* @throws MessagingException*/public static MimeMessage createFileMail(Session session)throws MessagingException {// 创建邮件对象MimeMessage message = new MimeMessage(session);// 指明发件人message.setFrom(new InternetAddress(sendEmailAccount));// 指明收件人message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiveMailAccount));// 可选 添加收件人
//        message.addRecipient(Message.RecipientType.TO, new InternetAddress("1499767535@qq.com"));//    Cc: 抄送(可选)
//        message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(receiveMailAccount));//    Bcc: 密送(可选)
//        message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(receiveMailAccount));// 邮件的标题message.setSubject(sendEmailSubject,"UTF-8");// 邮件的文本内容
//        message.setContent(sendEmailContext, "text/html;charset=UTF-8");// 设置显示发件时间message.setSentDate(new Date());// 创建消息部分BodyPart messageBodyPart = new MimeBodyPart();// 消息messageBodyPart.setText("This is message body");// 创建多重消息MimeMultipart multipart = new MimeMultipart();multipart.addBodyPart(messageBodyPart);// 附件部分messageBodyPart = new MimeBodyPart();String filePath = "C:\\Users\\YC01369\\Desktop\\file.txt";String fileName = "file.txt";DataSource source = new FileDataSource(filePath);messageBodyPart.setDataHandler(new DataHandler(source));messageBodyPart.setFileName(fileName);multipart.addBodyPart(messageBodyPart);// 发送完整消息message.setContent(multipart);return message;}

2 SpringBoot中操作邮箱

0 准备一个好的SpringBoot环境

1 添加maven坐标

    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>

2 添加发送邮箱接口

public interface MailService {/*** 发送邮件* @param to 接收者 邮件接收地址* @param subject 主题 邮件标题* @param content 内容 邮件正文* @param os 附件* @param attachmentFilename 附件名称* @throws Exception*/public void sendMail(String to, String subject, String content, ByteArrayOutputStream os,String attachmentFilename) throws Exception;}

3 添加发送邮箱实现类

@Component
@Slf4j
public class MailServiceImpl implements MailService {@Autowiredprivate JavaMailSender mailSender;@Value("${mail.fromMail.addr}")private String from;/*** * @param to 接收者 邮件接收地址* @param subject 主题 邮件标题* @param content 内容 邮件正文* @param os 附件* @param attachmentFilename 附件名称* @throws Exception*/@Overridepublic void sendMail(String to, String subject, String content, ByteArrayOutputStream os,String attachmentFilename) throws Exception {try {MimeMessage mimeMessage = mailSender.createMimeMessage();MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);mimeMessageHelper.setFrom(from);mimeMessageHelper.setTo(to);mimeMessageHelper.setSubject(subject);mimeMessageHelper.setText(content);// 判断附件是否存在if (null != os){InputStreamSource inputStreamSource = new ByteArrayResource(os.toByteArray());mimeMessageHelper.addAttachment(attachmentFilename, inputStreamSource);}mailSender.send(mimeMessage);log.info("邮件发送完成");} catch (Exception e) {log.error("邮件发送失败 , ={}",e);}}
}

4 添加配置文件

# 邮箱服务器地址
spring.mail.host=smtp.163.com
# 用户名
spring.mail.username=Xxx@163.com
# 密码
spring.mail.password=******
spring.mail.default-encoding=UTF-8
#spring.mail.port=587 # 使用报错
spring.mail.port=25   # 使用ok
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
# 来发送邮件账号
mail.fromMail.addr=Xxx@163.com

5 添加一个控制器

@Controller
@RequestMapping("/hello")
public class HelloWorld {public static String sendEmailSubject = "邮件的标题";public static String sendEmailContext = "邮件的内容";public static String receiveMailAccount = "Xxx@qq.com";@Autowiredprivate MailService mailService;@GetMapping("/sendMail")@ResponseBodypublic String sendMail() throws Exception {//  邮件接受者   邮件标题    邮件内容    附件   附件名称mailService.sendMail(receiveMailAccount,sendEmailSubject,sendEmailContext,null,"");return "<h1>Hello Wrold</h1>";}}

6 测试

在地址栏访问:

http://localhost:8080/hello/sendMail

控制台日志:

// 2021-11-01 18:04:41.535  INFO 16576 --- [nio-8080-exec-1] c.cf.demo.service.impl.MailServiceImpl   : 邮件发送完成

查看邮箱,邮件已送达.

3 错误问题

1 smtp.SMTPSendFailedException: 553 Mail from must equal authorized user

发邮件的人的账号填写错误, 要和授权码的账户一致.

// 接收邮件服务器:imap.qq.com,使用SSL,端口号993。// 发送邮件服务器:smtp.qq.com,使用SSL,端口号465或587。 使用25时成功

参考资料:

https://www.cnblogs.com/new-life/p/10549837.html

Java中邮箱的相关使用相关推荐

  1. Java中Date各种相关用法

    Java中Date各种相关用法 本文主要介绍Java中Date各种相关用法. AD:   Java中Date各种相关用法(一) 1.计算某一月份的最大天数 Java代码 Calendar time=C ...

  2. java中的字符串相关知识整理

    字符串为什么这么重要 写了多年java的开发应该对String不陌生,但是我却越发觉得它陌生.每学一门编程语言就会与字符串这个关键词打不少交道.看来它真的很重要. 字符串就是一系列的字符组合的串,如果 ...

  3. java中线程总结,JAVA中线程的相关小结

    ·什么是线程 线程:进程中负责程序执行的执行单元.一个进程中至少有一个线程. 多线程:一个进程中包含有多个线程,但CPU在同一时间只允许一个线程的进行.所以有多个线程的运行是根据CPU切换完成,如何切 ...

  4. Java中SMB的相关应用

    目录 SMB 服务操作 Ⅰ SMB简介 Ⅱ SMB配置 2.1 Windows SMB Ⅲ 添加SMB依赖 Ⅳ 路径格式 Ⅴ 操作共享 Ⅵ 登录验证 SMB 服务操作 Ⅰ SMB简介 ​ SMB(全称 ...

  5. JAVA中parameterized,Java中与泛型相关的接口 之 ParameterizedType

    在阅读本文之前可以先阅读以下三篇,以便对Java中的泛型有一个全局的认识: 简介 ParameterizedType是Type的子接口,表示一个有参数的类型,例如Collection,Map等.但实现 ...

  6. java中邮箱发送_java实现邮箱发送(java mail)

    导包:mail.jar import java.util.Properties; import javax.mail.Message; import javax.mail.Message.Recipi ...

  7. Java中的sqlsession_java相关:MyBatis中SqlSession实现增删改查案例

    java相关:MyBatis中SqlSession实现增删改查案例 发布于 2020-6-13| 复制链接 摘记: 前言     开博客这是第一次写系列文章,从内心上讲是有点担心自己写不好,写不全,毕 ...

  8. java中io流中显示中文_关于JAVA中IO流相关问题概述

    流是用于连接程序和设备之间的管道,主要用于数据传输.这个管道上有很多"按钮",每个"按钮"可以实现不同的功能. 四大基本抽象流:输入流,输出流,字节流,字符流 ...

  9. Java中StringBuffer的相关运用与实践

    文章目录 前言 一.准备工作 二. 开始写我们的程序 先看代码: 简单解说一下 总结 前言 hallo大家好,我是树树.今天树树来带大家通过学习StringBuffer中一些便利的用法来写一个信息的录 ...

最新文章

  1. 10个JavaScript难点
  2. 【转载】python3安装scrapy之windows32位爬坑
  3. http / 关于长连接和短链接的理解
  4. 关于Ueditor存储在mysqlUTF-8乱码的问题
  5. c++—简单的密码本实现
  6. python中不能使用下标运算的有哪些_Python中最常见的10个问题(列表)
  7. 深度学习能辨识壁画上的艺术元素吗?
  8. python中的成员运算符用于判断什么_Python3基础-表达式和运算符
  9. configure: error: C++ compiler cannot create executables
  10. python小学教材全解_小学教材全解五年级数学上人教版
  11. Oracle SOA平台1——概述
  12. 第三章 Guarded Suspension模式 等我准备好哦
  13. 什么是运维?运维工程师主要是做什么?
  14. 三年磨一剑大话数据结构——数据结构起源、概念和术语
  15. 咖啡汪日志—— 回退兜底 及实用的服务降级策略
  16. 微信退款提示NOTENOUGH:基本账户余额不足,充值后再退款提示可退金额剩余0
  17. 爬虫爬数据时,post数据乱码解决办法
  18. pdf ie中打开 会卡死
  19. kafka面试题知识点整理
  20. python3标识符类型_python – cython问题:’bool’不是一个类型标识符

热门文章

  1. 【Bug解决】invalid argument at /pytorch/aten/src /THC/THCGeneral.cpp:405
  2. 网络工程生产实习——构建中小型企业网(eNSP)
  3. 洛克人java下载_洛克人威利博士之谜
  4. java : apache cxf client 查询手机号码属地
  5. 2022年全球及中国公司秘书服务行业头部企业市场占有率及排名调研报告
  6. 原来你是这样的编辑器|CSDN编辑器测评
  7. 字体转换接口实现简体、繁体、火星文之间的转换
  8. gym101064L The Knapsack problem 超大容量完全背包
  9. java 16进制比较_java – 比较带符号的十六进制数
  10. Centos搬迁到openEuler详细指南