上一篇博文是生成pdf文档, 这篇文档跟大家分享一下怎么发送邮件,并且实现pdf作为附件的功能。
javaEmail的maven形式的jar包:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
首先是实现邮件发送功能的代码:
public void sendEmailAndPDF(SendEmailAndPDFReuqest sendEmailAndPDFReuqest, String fileLocalName) throws Exception {
logger.error("sendEmailAndPDF is keep on.....and fileLocalName is "+fileLocalName+"request is "+JsonUtils.objectToJson(sendEmailAndPDFReuqest));
EmailMessage emailMessage = new EmailMessage();
StringBuffer sb = new StringBuffer();
String orderNo = sendEmailAndPDFReuqest.getResp().getMainOrderNo();
sb.append(orderNo);
emailMessage.setSubject(String.format("订单号:%s预订确认", sb)); //邮箱标题
emailMessage.setContext(sendOrderDeatilAndPDFContext.buildContext(sendEmailAndPDFReuqest));//邮箱正文,我这个正文很简单,就不上代码了,就是一些html标签+文字描述
emailMessage.setBodyHtml(true);
Vector<String> file = new Vector<String>();//保存多个需上传附件的文件名
file.add(fileLocalName);
emailMessage.setFile(file);
emailProvider.sendEmailAndPDF(emailMessage, sendEmailAndPDFReuqest.getResp().getSupplier(),sendEmailAndPDFReuqest.getProviderEmail());
}
email.setEmailReceiver(); //设置邮箱接收者
sendEmail(email);
//下面是主要的发送代码:
private String host = "smtp.****.com.cn"; //这是smtp协议的邮箱服务器主机,每个公司都不一样
private int port = 27;
private String auth = "true";
private String userName = "frank.***@****.com"; //公司哟向服务器主机的账号
private String password = ""; //密码
private String sendMailAddress = "****"; //发送的邮件名,一般的用公司名义去申请的邮箱
Logger logger = LoggerFactory.getLogger(this.getClass());
public void sendEmail(EmailMessage email) throws Exception{
logger.error("createSendEmail is starting........email is "+JsonUtils.objectToJson(email));
System.setProperty("mail.mime.charset","UTF-8");
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", auth);
Session s = Session.getInstance(props);
MimeMessage message = new MimeMessage(s);
InternetAddress from = new InternetAddress(sendMailAddress);
message.setFrom(from);
message.addRecipients(Message.RecipientType.TO, email.getAddress());//邮箱接收者
message.setSubject(email.getSubject());
message.setSentDate(new Date());
Multipart mp = new MimeMultipart();
if(!email.getFile().isEmpty()){//有附件
Enumeration<String> efile=email.getFile().elements();
while(efile.hasMoreElements()){
MimeBodyPart mbp=new MimeBodyPart();
String filename=efile.nextElement(); //选择出每一个附件名
FileDataSource fds= new FileDataSource(filename); //得到数据源
mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart
mbp.setFileName(MimeUtility.encodeText(fds.getName())); //得到文件名同样至入BodyPart
mp.addBodyPart(mbp);
}
email.getFile().removeAllElements();
}
if (email.isBodyHtml()) {
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(email.getContext(), "text/html;charset=utf-8");
mp.addBodyPart(mbp);
message.setContent(mp);
} else{
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(email.getContext(), "text/plain;charset=utf-8");
mp.addBodyPart(mbp);
message.setContent(mp);
}
message.saveChanges();
Transport transport = s.getTransport("smtp");//创建邮箱服务器通道的协议
transport.connect(host, port, userName, password);//设置连接的主机号端口号账号和密码
logger.error(" and message.getAllRecipients is "+ message.getAllRecipients() != null ? JsonUtils.objectToJson(message.getAllRecipients()):"");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
logger.info("email send tips: email from " + userName + " to " + email.getEmailReceiver());
}
这样就能完成一个邮箱发送的基础功能,下面就来看看怎么讲在代码中生成的pdf发到附件中?
其实上面的代码已经实现了。
因为之前已经生成了pdf文档,但是并没有在没有返回页面之前,还是在response中的输出流中,但是Email的的实体类只接受文件名的形式,
之前想过将response中的输出流转换成输入流或者字节流来做, 转换成字节流的byteinputstream只能从高速缓存中读取, 而httpservletReponse中读取不到,
这边用的办法是将response先写到默认的文件路中 System.getProperty("java.io.tmpdir");
就是在系统的C:\Users\mars\AppData\Local\Temp,这个地址是jvm默认的临时文件存放地址,
上一篇文章有这一步,如下: 将pdfWrite写入文件输入流中输出到系统临时文件地址下,
FileOutputStream fos = new FileOutputStream(file);
if(type.equals(DOWNLOAD_PDF)){
PdfWriter.getInstance(document, response.getOutputStream());//用于返回页面下载
}else if(type.equals(SEND_PDF)){
PdfWriter.getInstance(document, fos);//用于邮件附件获取
}
Vector<String> file = new Vector<String>();//保存多个需上传附件的文件名
file.add(fileLocalName);
emailMessage.setFile(file);
通过方法去获取对应文件名和地址的文件作为附件,实现了附件上传
if(!email.getFile().isEmpty()){//有附件
Enumeration<String> efile=email.getFile().elements();
while(efile.hasMoreElements()){
MimeBodyPart mbp=new MimeBodyPart();
String filename=efile.nextElement(); //选择出每一个附件名
FileDataSource fds= new FileDataSource(filename); //得到数据源
mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart
mbp.setFileName(MimeUtility.encodeText(fds.getName()));
mp.addBodyPart(mbp);
}
email.getFile().removeAllElements(); }