当前位置:   article > 正文

JAVA之发送邮件_java 发送邮件

java 发送邮件

发送邮件javamail

一、导入依赖

<dependency>
      <groupId>javax.mail</groupId>  
      <artifactId>mail</artifactId>  
      <version>1.4.7</version>  
</dependency>  
  • 1
  • 2
  • 3
  • 4
  • 5

二、发送普通文本

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);
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

三、发送附件

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);
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

发送邮件commons-email

一、导入依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-email</artifactId>
    <version>1.4</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

二、发送普通文本

	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();
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

三、发送附件

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();
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

通过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));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

全部代码如下:

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();
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130

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

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/591883
推荐阅读
相关标签
  

闽ICP备14008679号