JAVA之发送邮件

发送邮件javamail

一、导入依赖

<dependency>
      <groupId>javax.mail</groupId>  
      <artifactId>mail</artifactId>  
      <version>1.4.7</version>  
</dependency>  

二、发送普通文本

public static void testSendTextMail() throws Exception {
		// 1、创建Session Properties props,Authenticator auth

		Properties props = new Properties();

		props.setProperty("mail.host", "smtp.qq.com");// 发送的服务器主机地址

		props.setProperty("mail.smtp.auth", "true");// 通过服务器的认证

		Authenticator auth = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				// 封装了发件人的用户名和密码(如果是qq有个授权码,不是写qq密码)
				return new PasswordAuthentication("xx用户名", "xx密码");
			}
		};

		Session session = Session.getInstance(props, auth);

		// 2、创建MimeMessage
		MimeMessage msg = new MimeMessage(session);

		// 设置发件人
		msg.setFrom(new InternetAddress("xx@qq.com"));
		// 垃圾邮件解决问题:抄送人添加自己
		// 设置收件人
		// TO收件人 CC抄送人 BCC密送
		msg.setRecipient(RecipientType.TO, new InternetAddress("xx@qq.com"));

		// 设置邮件的标题
		msg.setSubject("测试邮件的标题");

		// 设置邮件的内容
		msg.setContent("测试邮件的内容", "text/html;charset=utf-8");

		// 3、发送 TrancePort
		Transport.send(msg);
	}

三、发送附件

public static void testSendFileMail() throws Exception {
		// 1、创建Session Properties props,Authenticator auth

		Properties props = new Properties();

		props.setProperty("mail.host", "smtp.qq.com");// 发送的服务器主机地址

		props.setProperty("mail.smtp.auth", "true");// 通过服务器的认证

		Authenticator auth = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				// 封装了发件人的用户名和密码
				return new PasswordAuthentication("xx", "xx");
			}
		};

		Session session = Session.getInstance(props, auth);

		// 2、创建MimeMessage
		MimeMessage msg = new MimeMessage(session);

		// 设置发件人
		msg.setFrom(new InternetAddress("xx@qq.com"));
		// 垃圾邮件解决问题:抄送人添加自己
		// 设置收件人
		// TO收件人 CC抄送人 BCC密送
		msg.setRecipient(RecipientType.TO, new InternetAddress("xx@qq.com"));

		// 设置邮件的标题
		msg.setSubject("测试邮件的标题");
		
		// 部件对象
		MimeMultipart multipart = new MimeMultipart();
		
		// 可以是普通文本内容也可以是附件
		MimeBodyPart part = new MimeBodyPart();
		
		part.setContent("测试测试","text/html;charset=utf-8");
		
		MimeBodyPart part2 = new MimeBodyPart();
		
		part2.attachFile("D:\\Study\\Back-end\\EasyTest.xlsx");
		
		part2.setFileName(MimeUtility.encodeText("附件的名字xx.xlsx"));//中文会出问题
		
		multipart.addBodyPart(part);
		
		multipart.addBodyPart(part2);

		// 设置邮件的内容为附件
		msg.setContent(multipart);

		// 3、发送 TrancePort
		Transport.send(msg);
	}

发送邮件commons-email

一、导入依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-email</artifactId>
    <version>1.4</version>
</dependency>

二、发送普通文本

	public static void testSendCommonTextMail() throws Exception {
		SimpleEmail email = new SimpleEmail();//发送普通邮件
		
//		email.setTLS(true);//设置认证
		
		email.setHostName("smtp.qq.com");//发送方的邮件服务器
		
		email.setAuthentication("xx", "xx");//设置登录的账号密码
		
//		email.setFrom("xx@qq.com");
		email.setFrom("xx@qq.com", "一个名字xx", "utf-8");//设置发送方,给发送方指定名字
		
		email.addTo("xx@qq.com");//设置接收方
		
		email.setSubject("邮件主题xxx");//设置邮件主题
		
		email.setContent("邮件内容xx","text/html;charset=utf-8");//设置邮件内容
		
		email.send();
	}

三、发送附件

public static void testSendCommonFileMail() throws Exception {
		// TODO Auto-generated method stub
		MultiPartEmail email = new MultiPartEmail();
		
//		email.setTLS(true);//设置认证
		
		email.setHostName("smtp.qq.com");//发送方的邮件服务器
		
		email.setAuthentication("xx", "xx");//设置登录的账号密码
		
//		email.setFrom("xx@qq.com");
		email.setFrom("xx@qq.com", "一个名字xx", "utf-8");//设置发送方,给发送方指定名字
		
		email.addTo("xx@qq.com");//设置接收方
		
		email.setSubject("带附件主题");//设置邮件主题
		
		email.setCharset("utf-8");
		
		email.setMsg("带附件的内容内容xx"); // 发附件的时候不能用setContent方法,否则不显示附件
		
		EmailAttachment attachment = new EmailAttachment();
		
		attachment.setPath("D:\\Study\\Back-end\\EasyTest.xlsx");
		
		attachment.setName(MimeUtility.encodeText("附件名字.xlsx"));
		
		// 把附件添加到email对象上
		email.attach(attachment);
		
		email.send();
	}

通过POI将数据导出成excel模板并当成附件进行邮件发送

方法一:通过POI读取数据库的数据,并生成excel,但不保存在本地文件,通过流的方式,作为附件并发送邮件
主要的代码如下:

//1、将导出的数据变成流
ByteArrayOutputStream os = new ByteArrayOutputStream();
workbook.write(os);
workbook.close();
ByteArrayInputStream iss = new ByteArrayInputStream(os.toByteArray());
os.close();
//2、将流变成要发送的文件
DataSource files =  new ByteArrayDataSource(iss, "application/vnd.ms-excel;charset=UTF-8");
//3、设置文件为附件
part.setDataHandler(new DataHandler(files));

全部代码如下:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
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.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;

public class TestPOISendMail {
	public static void testPOIAndSendMail() throws Exception {

		// 1、创建一个工作簿 07
		Workbook workbook = new XSSFWorkbook();
		// 2、创建一个工作表
		Sheet sheet = workbook.createSheet("xxms观众统计表");
		// 3、创建一个行
		Row row1 = sheet.createRow(0);
		// 4、创建一个单元格 (1,1)
		Cell cell11 = row1.createCell(0);
		cell11.setCellValue("今日新增观众");
		// (1,2)
		Cell cell12 = row1.createCell(1);
		cell12.setCellValue(666);

		// 第二行
		Row row2 = sheet.createRow(1);
		// (2,1)
		Cell cell21 = row2.createCell(0);
		cell21.setCellValue("统计时间");
		// (2,2)
		Cell cell22 = row2.createCell(1);
		String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
		cell22.setCellValue(time);

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		workbook.write(os);
		workbook.close();
		// 重置流
		// os.reset();
		ByteArrayInputStream iss = new ByteArrayInputStream(os.toByteArray());
		os.close();
		testSendFileMail(iss);
	}

	public static void testSendFileMail(ByteArrayInputStream iss) throws Exception {
		
		// 1、创建Session Properties props,Authenticator auth
		Properties props = new Properties();

		props.setProperty("mail.host", "smtp.qq.com");// 发送的服务器主机地址

		props.setProperty("mail.smtp.auth", "true");// 通过服务器的认证

		Authenticator auth = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				// 封装了发件人的用户名和密码
				return new PasswordAuthentication("xx", "xx");
			}
		};
		

		Session session = Session.getInstance(props, auth);
		
		session.setDebug(true);

		// 2、创建MimeMessage
		MimeMessage msg = new MimeMessage(session);

		// 设置发件人
		msg.setFrom(new InternetAddress("xx@qq.com"));
		// 垃圾邮件解决问题:抄送人添加自己
		// 设置收件人
		// TO收件人 CC抄送人 BCC密送
		msg.setRecipient(RecipientType.TO, new InternetAddress("xx@qq.com"));

		// 设置邮件的标题
		msg.setSubject("x月份数据");
		
		
		// 部件对象
		MimeMultipart multipart = new MimeMultipart();
		
		// 可以是普通文本内容也可以是附件
		MimeBodyPart part = new MimeBodyPart();
		
		DataSource files =  new ByteArrayDataSource(iss, "application/vnd.ms-excel;charset=UTF-8");
		part.setDataHandler(new DataHandler(files));
		part.setFileName(MimeUtility.encodeText("x月份数据1.xlsx"));
		
		MimeBodyPart part2 = new MimeBodyPart();
		part2.setDataHandler(new DataHandler(files));
		part2.setFileName(MimeUtility.encodeText("x月份数据2.xlsx"));
		
		MimeBodyPart part3 = new MimeBodyPart();
		part3.setContent("请查收","text/html;charset=utf-8");
		
		multipart.addBodyPart(part);
		multipart.addBodyPart(part2);
		multipart.addBodyPart(part3);

		// 设置邮件的内容为附件
		msg.setContent(multipart);

		// 3、发送 TrancePort
		Transport.send(msg);
	}

	public static void main(String[] args) throws Exception {
		testPOIAndSendMail();
	}
}

方法二:将导出的数据生成文件,将该文件发送出去后,再删除该文件
主要代码如下:

String filePath = "D:\\Work-IT\\data.xlsx";
try (FileOutputStream fos = new FileOutputStream(new File(filePath))) {
	workbook.write(fos);
} catch (Exception e) {
	logger.error("Excel文件生成异常……", e);
}
// ..正常发送该文件
File file = new File(filePath);
if (file.exists()) {
	file.delete();
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值