资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

JAVA之发送邮件-创新互联

发送邮件javamail

一、导入依赖

10年积累的成都网站设计、成都做网站经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先做网站设计后付款的网站建设流程,更有郾城免费网站建设让你可以放心的选择与我们合作。
javax.mailmail1.4.7

二、发送普通文本

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

一、导入依赖

org.apache.commonscommons-email1.4

二、发送普通文本

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();
}

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


网站标题:JAVA之发送邮件-创新互联
URL网址:http://cdkjz.cn/article/dgdhsp.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220