注意:本文只打算讨论JavaMail收发带附件邮件的一些技巧,所以只是给出部分代码。
1.发送带附件的邮件
我们平时发送的邮件主要可以分解成2大部分,一个是发信人,接信人,主题等邮件标头,另外一部分是邮件内容,它包括了邮件的附件。我们在发送普通邮件的时候content设置的类型是"text/html",带上附件后,我们需要把content的类型设置成Multipart,这时content包括了附件和"text/html"类型的正文。下面的这个告诉大家如何把附件放置到邮件中。
private Multipart getMultipart() throws MessagingException,UnsupportedEncodingException { MimeMultipart mp = new MimeMultipart(); try { //设置content里的内容 MimeBodyPart contentMbp = new MimeBodyPart(); //请指定字符集,否则会是乱码 contentMbp.setContent(_mailContent.getContent(), "text/html; charset=GB2312"); mp.addBodyPart(contentMbp); //添加附件 for (int i=0;i<_mailAttachment.getAttachPath().size();i++) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource((String) _mailAttachment.getAttachPath().get(i)); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(MimeUtility.encodeWord(fds.getName(), "GB2312",null)); mp.addBodyPart(mbp); } } catch(MessagingException ie) { System.out.println("Set Content Message error..."+ie.getMessage()); throw ie; } catch(UnsupportedEncodingException ie) { System.out.println("Encode the fileName error..."+ie.getMessage()); throw ie; } return mp; } 放置附件的注意事项如下: 在发mail时需要注意字符集的问题。不但content里要设置,而且文件名也需要设置。如果我们去掉mbp.setFileName(MimeUtility.encodeWord(fds.getName(),"GB2312",null));这句话,那么你选中的附件还是会带到邮件里,但是在附件里看不到。我们可以通过查看邮件大小知道。我们利用这个特点来实现发送content中写的是html语言,而且包含图片信息的邮件。
15b
Copyright @ 2007-2012 敏韬网(敏而好学,文韬武略--MinTao.Net)(学习笔记) Inc All Rights Reserved. 闵涛 E_mail:admin@mintao.net(欢迎提供学习资源)
鄂公网安备 42011102001154号
站长:MinTao ICP备案号:鄂ICP备11006601号-18