1、小编用的是163邮箱发送邮件,所以要先登录163邮箱开启POP3/SMTP/IMAP服务方法:

2、下载所需的java-mail 包

https://maven.java.net/content/repositories/releases/com/sun/mail/javax.mail/

3、贴上代码

public class sendMail {
/**
* 创建邮件信息
* @param session
* @param fromAccount
* @param toAccount
* @param sourcePath xml文件目录 e.g. xml
* @param zipPath zip文件目录 e.g. zip/person.zip
*/
public static void CreateMessage(final Session session, final String fromAccount, final String toAccount,final String sourcePath,final String zipPath){
try{
final String subjectStr="圣诞节快乐";//主题
final StringBuffer contentStr=new StringBuffer();//内容
contentStr.append("<h2>Dear Friends,</h2><br/>");
contentStr.append("Christmas is coming up soon. <br/> Wish you lots of love, joy &happiness. happy christmas.");
contentStr.append("<h3>Regards,</h3>").append("<h3>ZHBIT College</h3>"); //创建默认的 MimeMessage 对象
final MimeMessage message = new MimeMessage(session);
//Set From: 头部头字段
message.setFrom(new InternetAddress(fromAccount));
//Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(toAccount));
//Set Subject: 头部头字段
message.setSubject(subjectStr);
//创建消息部分
final BodyPart messageBodyPart = new MimeBodyPart();
//消息
messageBodyPart.setContent(contentStr.toString(),"text/html;charset=UTF-8");
//创建多重消息
final Multipart multipart = new MimeMultipart();
//设置文本消息部分
multipart.addBodyPart(messageBodyPart);
//为邮件添加多个附件
MimeBodyPart attachment = null;
final File source = new File(sourcePath);
if (!source.exists()) {
System.out.println(sourcePath + " not exists");
return;
}
final File[] files = source.listFiles();
for (final File f : files) {
attachment = new MimeBodyPart();
final String filePath =f.getPath();
//根据附件文件创建文件数据源
final DataSource ds = new FileDataSource(filePath);
attachment.setDataHandler(new DataHandler(ds));
//为附件设置文件名
attachment.setFileName(ds.getName());
multipart.addBodyPart(attachment);
} //添加zip附件
attachment = new MimeBodyPart();
//根据附件文件创建文件数据源
final DataSource ds = new FileDataSource(zipPath);
attachment.setDataHandler(new DataHandler(ds));
//为附件设置文件名
attachment.setFileName(ds.getName());
multipart.addBodyPart(attachment); // 发送完整消息
message.setContent(multipart);
// 发送消息
Transport.send(message); }catch (final MessagingException mex) {
mex.printStackTrace();
}
} /**
* 将源文件目录下的所有文件打包成zip文件
* @param sourceFilePath e.g. xml
* @param zipFilePath e.g. zip
* @param fileName e.g. person
* @return 返回生成的zip文件目录 e.g. zip/person.zip
*/
public static String tozip(final String sourceFilePath, final String zipFilePath,
final String fileName) {
final File sourceFile = new File(sourceFilePath);
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
final String createZipPath=zipFilePath+ "/" + fileName+ ".zip"; if(!sourceFile.exists()){
System.out.println("待压缩的文件目录:" + sourceFilePath + "不存在");
} else {
try {
final File zipFile = new File(createZipPath);
final File[] sourceFiles = sourceFile.listFiles();
if(null == sourceFiles || sourceFiles.length < 1) {
System.out.println("待压缩的文件目录:" + sourceFilePath + " 里面不存在文件,无需压缩");
}else{
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
final byte[] bufs = new byte[1024*10];
for(int i=0;i<sourceFiles.length;i++) {
// 创建ZIP实体,并添加进压缩包
final ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis,1024*10);
int read = 0;
while((read=bis.read(bufs, 0, 1024*10)) != -1) {
zos.write(bufs, 0, read);
}
}
} } catch (final FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (final IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try {
if (null != bis) {
bis.close();
}
if (null != zos) {
zos.close();
}
} catch (final IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
return createZipPath;
} public static void main(final String[] args) {
//收件人电子邮箱
final String toAccount = "********@qq.com";
//发件人的 邮箱 和 密码
final String fromAccount = "**********@163.com";
final String fromPassword = "**********";
//指定发送邮件的主机
final String host = "smtp.163.com"; //创建参数配置, 获取系统属性
final Properties properties = System.getProperties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true"); //根据配置创建会话对象,获取默认session对象
final Session session = Session.getDefaultInstance(properties,new Authenticator(){
@Override
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(fromAccount, fromPassword); //发件人邮件用户名、密码
}
});
session.setDebug(true); final String xmlPath="xml";
final String zipPath=tozip(xmlPath,"zip","person");
CreateMessage(session,fromAccount,toAccount,xmlPath,zipPath);
} }

4、收到邮件

Java Mail 发送带有附件的邮件的更多相关文章

  1. 解决java mail发送TXT附件被直接显示在正文中的问题

    这两天遇到一个问题,关于使用java mail发送邮件的问题. 详细是这样子的:我使用java mail发送异常报告邮件,邮件中有一个包含异常日志的附件,和关于设备信息的邮件正文.假设日志为log后缀 ...

  2. Android在发送带有附件的邮件

    准备好工作了-下载最新的版本号JMail https://java.net/projects/javamail/pages/Home#Download_JavaMail_1.5.2_Release h ...

  3. java mail发送html格式的邮件

    // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("ma ...

  4. spring boot:发送带附件的邮件和html内容的邮件(以163.com邮箱为例/spring boot 2.3.2)

    一,网站哪些情况下需要发送电子邮件? 作为一个电商网站,以下情况需要发邮件通知用户: 注册成功的信息 用邮箱接收验证码 找回密码时发链接 发送推广邮件 下单成功后的订单通知 给商户的对账单邮件 说明: ...

  5. 【Mail】JavaMail发送带附件的邮件(二)

    上一篇讲了使用JavaMail发送普通邮件([Mail]JavaMail介绍及发送邮件(一)),本例讲发送复杂的邮件(带有附件的邮件) 生成一封复杂的邮件 新建一个JavaWeb的Maven工程,引入 ...

  6. java发送带附件的邮件

    /** * java发送带附件的邮件 * 周枫 * 2013.8.10 */ package com.dsideal.Util; import javax.mail.*; import javax.m ...

  7. [Xcode 实际操作]八、网络与多线程-(7)使用MessageUI框架,创建并发送一封带有附件的邮件

    目录:[Swift]Xcode实际操作 本文将演示如何使用MessageUI框架,创建并发送一封带有附件的邮件. 使用邮件编辑视图控制器(MFMailComposeViewController)实现邮 ...

  8. [SpringBoot] - 发送带附件的邮件

    <!--发送email依赖--> <dependency> <groupId>org.springframework.boot</groupId> &l ...

  9. 利用Python+163邮箱授权码发送带附件的邮件

    背景 前段时间写了个自动爬虫的脚本,定时在阿里云服务器上执行,会从某个网站上爬取链接保存到txt文本中,但是脚本不够完善,我需要爬虫完毕之后通过邮件把附件给我发送过来,之前写过一个<利用Pyth ...

随机推荐

  1. 负载均衡服务之HAProxy基础配置(五)

    前文我们聊了下haproxy的修改报文首部的配置.压缩功能以及haproxy基于http协议自定义健康状态检测机制:回顾请参考https://www.cnblogs.com/qiuhom-1874/p ...

  2. 用python把技术文档中,每个模块系列截图生成一个动态GIF

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 最近在写技术文档的时候,发现一个问题.对于每个技术步骤,都需要一个截图,这 ...

  3. 从零开始学习docker之在docker中搭建redis(单机)

    docker搭建redis 一.环境准备 云环境:CentOS 7.6 64位 二.下载镜像 从docker hub中找到redis镜像 传送门------https://hub.docker.com ...

  4. php +go关键字实现协程

    来源: https://studygolang.com/articles/17631?fr=sidebar 今天在知乎浏览时忽然发现了一个有趣的东西,php竟然可以实现协程的实现,而且还是通过go关键 ...

  5. 关于XSS弹窗的小姿势

    最近快比赛了想刷刷题,做合天XSS进阶的时候遇到了过滤了alert然后还要弹窗效果的题目,这让我这个JS只学了一点点的菜鸡倍感无力.     在百度了其他资料后,发现confirm('xss')和pr ...

  6. Libra白皮书解读

    文章目录 Libra简介 Libra区块链 Libra货币和存储 Libra协会 Libra简介 Libra是facebook发起的一个区块链项目,其使命是建立一套简单的.无国界的货币和为数十亿人服务 ...

  7. BootStrap的栅格式布局

    1.栅格系统(布局) Bootstrap内置了一套响应式.移动设备优先的流式栅格系统,随着屏幕设备或视口(viewport)尺寸的增加,系统会自动分为最多12列. 我在这里是把Bootstrap中的栅 ...

  8. mac OS vi/vim 使用教程

    vi/vim 的使用 基本上 vi/vim 共分为三种模式 分别是 命令模式(Command mode) 输入模式(Insert mode) 底线命令模式(Last line mode) 命令模式: ...

  9. 内蒙古特检院利用物联网/RFID技术提高电梯检测水平

    随着电梯检验工作信息化进程的进一步深入,内蒙古特检院从检验工作中寻找新方法.新手段,为检验员新引入电梯检验手持终端设备,力求提高电梯检验水平,将"电梯安全惠民工程"落到实处. 电梯 ...

  10. KAFKA官方教程笔记-introduction

    为什么80%的码农都做不了架构师?>>>   介绍 apache kafka是一个分布式流式处理平台,一个流式平台该有的三个关键能力: 发布.订阅流式数据.从这个角度讲类似消息队列或 ...