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 authProperties 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、创建MimeMessageMimeMessage 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、发送 TrancePortTransport.send(msg);}

三、发送附件

public static void testSendFileMail() throws Exception {// 1、创建Session Properties props,Authenticator authProperties 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、创建MimeMessageMimeMessage 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、发送 TrancePortTransport.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 stubMultiPartEmail 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、创建一个工作簿 07Workbook 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 authProperties 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、创建MimeMessageMimeMessage 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、发送 TrancePortTransport.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();
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部