前言
电子邮件在网络中传输和网页一样需要遵从特定的协议,常用的电子邮件协议包括 SMTP,POP3,IMAP。其中邮件的创建和发送只需要用到 SMTP协议,所以本文也只会涉及到SMTP协议。SMTP 是 Simple Mail Transfer Protocol 的简称,即简单邮件传输协议。
javaMail
Java 官方提供了对电子邮件协议封装的 Java 类库,就是JavaMail,支持SMTP,IMAP和POP3协议的实现
引入jar
依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.3</version>
</dependency>
调用方法
try {
MailBean mb = new MailBean();
mb.setTo("xx@xx.com"); // 接收地址
Calendar c = Calendar.getInstance();
Date date = new Date();
c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day - 1);
String trxDate = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
String dateStart = trxDate + " 00:00:00";
String dateEnd = trxDate + " 23:59:59";
List<Map<String, Object>> list =xxDao.getByxx("xx",dateStart,dateEnd);
logger.info("查到的xx数量为:" + list.size());
String filePath = ExcelForExport.exportExcel(list, "数据" + DateUtil.formatNow("yyyyMMdd"));
mb.attachFile(filePath); 添加附件
mb.setHost("smtp.qiye.163.com"); 设置SMTP主机(163),若用126,则设为:smtp.126.com
mb.setUsername("xx@xx.com"); 设置发件人邮箱的用户名
mb.setPassword("*********"); 设置发件人邮箱的密码,需将*号改成正确的密码
mb.setFrom("xx@xx.com"); 设置发件人的邮箱
mb.setCopyColumn("xx@xx.com"); 设置抄送人
mb.setCopyColumn("xx@xx.com"); 设置抄送人
mb.setSubject("案例"); 设置邮件的主题
mb.setContent("案例明细,请查收附件"); 设置邮件的正文
SendMail sm = new SendMail();
if (sm.sendMail(mb)) { 发送邮件
logger.info("案例明细 sendEmail success");
} else {
logger.error(" sendEmail fail ");
}
} catch (Exception e) {
logger.error(e.getMessage());
logger.error(" sendEmail fail ");
}
工具类
MailBean.java
package com.rs.common.mail;
import java.util.Vector;
public class MailBean {
Vector<String> to; // 收件人
private String from; // 发件人
Vector<String> copyColumn; // 抄送人
private String host; // SMTP主机
private String username; // 发件人的用户名
private String password; // 发件人的密码
private String subject; // 邮件主题
private String content; // 邮件正文
Vector<String> file; // 多个附件
private String filename; // 附件的文件名
public Vector<String> getTo() {
return to;
}
public void setTo(String toName) {
if(to==null){
to = new Vector<String>();
}
to.addElement(toName);
}
public Vector<String> getCopyColumn(){
return copyColumn;
}
public void setCopyColumn(String ccName){
if(copyColumn==null){
copyColumn = new Vector<String>();
}
copyColumn.addElement(ccName);
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Vector<String> getFile() {
return file;
}
public void attachFile(String fileName) {
if (file == null)
file = new Vector<String>();
file.addElement(fileName);
}
}
SendMail.java
package com.rs.common.mail;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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.MimeMultipart;
import org.apache.commons.codec.binary.Base64;
public class SendMail {
public boolean sendMail(MailBean mb) {
String host = mb.getHost();
final String username = mb.getUsername();
final String password = mb.getPassword();
String from = mb.getFrom();
String subject = mb.getSubject();
String content = mb.getContent();
String fileName = mb.getFilename();
Vector<String> file = mb.getFile();
Properties props = new Properties();
// mail.smtp.host
props.setProperty("mail.smtp.host", host); // 设置SMTP的主机
props.setProperty("mail.smtp.auth", "true"); // 需要经过验证
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "25");
props.setProperty("mail.smtp.socketFactory.port", "25");
//Session s = Session.getInstance(props, null);
Session session = Session.getInstance(props, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
MimeMessage msg = new MimeMessage(session);
// 设置多个收件人地址
List<String> list = mb.getTo();
String toAddress = getAddress(list);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = InternetAddress.parse(toAddress);
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
// 设置抄送人
if (mb.getCopyColumn() != null) {
msg.setRecipients(Message.RecipientType.CC,
(Address[]) InternetAddress.parse(getAddress(mb.getCopyColumn())));
}
Multipart mp = new MimeMultipart();
MimeBodyPart mbpContent = new MimeBodyPart();
mbpContent.setText(content);
mp.addBodyPart(mbpContent);
/* 往邮件中添加附件 */
if (file != null) {
Enumeration<String> efile = file.elements();
while (efile.hasMoreElements()) {
MimeBodyPart mbpFile = new MimeBodyPart();
fileName = efile.nextElement().toString();
FileDataSource fds = new FileDataSource(fileName);
mbpFile.setDataHandler(new DataHandler(fds));
try {
mbpFile.setFileName("=?GBK?B?"
+ Base64.encodeBase64String(fds.getName().getBytes("GBK"))
+ "?=");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mp.addBodyPart(mbpFile);
}
}
msg.setContent(mp);
msg.setSentDate(new Date());
Transport.send(msg);
} catch (MessagingException me) {
me.printStackTrace();
return false;
}
return true;
}
public String getAddress(List<String> list){
String address = "";
for (String string : list) {
address += string + ",";
}
return address;
}
}
ExcelForExport.java
package com.middlepay.common.util;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import java.lang.reflect.Field;
import java.net.SocketException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExcelForExport {
public static final Log logger = LogFactory.getLog(ExcelForExport.class);
public static String exportExcel(List<Map<String, Object>> list1, String fileName) throws Exception {
File file = new File("/usr/local/report_excl/" + fileName + ".xlsx");
String[] firstcellName = {"","", "", "","","", ""};
String[] firstcellValue = {"","", "","","","", ""};
// File file = new File("C:/certs/test/" + fileName + ".xls");
if (!file.exists()) {
file.createNewFile();
}
// 声明一个工作薄
SXSSFWorkbook workbook = new SXSSFWorkbook();
// 生成一个表格
Sheet sheet = workbook.createSheet(fileName);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 15);
// 生成一个样式
CellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
Font font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
// 生成并设置另一个样式
CellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.WHITE.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一个字体
Font font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字体应用到当前的样式
style2.setFont(font2);
Font font3 = workbook.createFont();
font3.setColor(HSSFColor.BLACK.index);
// 声明一个画图的顶级管理器
// HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 定义注释的大小和位置,详见文档
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
0, 0, 0, (short) 4, 2, (short) 6, 5));
// 设置注释内容
comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
// 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
comment.setAuthor("leno");
// 产生表格标题行
Row row = sheet.createRow(0);
for (short i = 0; i < firstcellName.length; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(style);
XSSFRichTextString text = new XSSFRichTextString(firstcellName[i]);
cell.setCellValue(text);
}
Iterator<Map<String, Object>> it = list1.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
Map<String, Object> map = it.next();
for (int i = 0; i < firstcellValue.length; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(style2);
XSSFRichTextString richString = new XSSFRichTextString(
map.get(firstcellValue[i]) + "");
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
OutputStream outXlsx = new FileOutputStream(file);
workbook.write(outXlsx);
outXlsx.flush();
outXlsx.close();
return "/usr/local/report_excl/" + fileName + ".xlsx";
}
}
结尾
以上就是使用java发送邮件(添加附件)的一次实例