当前位置: 代码迷 >> J2SE >> 怎么获得邮件文件的附件
  详细解决方案

怎么获得邮件文件的附件

热度:10   发布时间:2016-04-24 01:02:42.0
如何获得邮件文件的附件
如何获得邮件文件的附件,比如有一个eml的邮件文件,里面带有附件,一个或者多个,如何获得这些附件?需要程序实现,给个方法,Java、C都可

------解决方案--------------------
发送带有附件的邮件
发送带有附件的邮件的过程有些类似转发邮件,我们需要建立一个完整邮件的各个邮件体部分,在第一个部分(即我们的邮件内容文字)后,增加一个具有DataHandler的附件而不是在转发邮件时那样复制第一个部分的DataHandler。

如果我们将文件作为附件发送,那么要建立FileDataSource类型的对象作为附件数据源;如果从URL读取数据作为附件发送,那么将要建立URLDataSource类型的对象作为附件数据源。

然后将这个数据源(FileDataSource或是URLDataSource)对象作为DataHandler类构造方法的参数传入,从而建立一个DataHandler对象作为数据源的DataHandler。

接着将这个DataHandler设置为邮件体部分的DataHandler。这样就完成了邮件体与附件之间的关联工作,下面的工作就是BodyPart的setFileName()方法设置附件名为原文件名。

最后将两个邮件体放入到Multipart中,设置邮件内容为这个容器Multipart,发送邮件。
Java code
// Define messageMessage message = new MimeMessage(session);message.setFrom(new InternetAddress(from));message.addRecipient(Message.RecipientType.TO,   new InternetAddress(to));message.setSubject("Hello JavaMail Attachment");// Create the message part BodyPart messageBodyPart = new MimeBodyPart();// Fill the messagemessageBodyPart.setText("Pardon Ideas");Multipart multipart = new MimeMultipart();multipart.addBodyPart(messageBodyPart);// Part two is attachmentmessageBodyPart = new MimeBodyPart();DataSource source = new FileDataSource(filename);messageBodyPart.setDataHandler(new DataHandler(source));messageBodyPart.setFileName(filename);multipart.addBodyPart(messageBodyPart);// Put parts in messagemessage.setContent(multipart);// Send the messageTransport.send(message);
------解决方案--------------------
没做过,但是感觉可以自己解析。打开邮件文件,可以看到基本的邮件结构,其中附件肯定是以BASE64编码放在后面的,把它读出来解析,按照邮件中的文件名存储就可以了。
------解决方案--------------------
学习
------解决方案--------------------
我编过一个从邮箱里获取邮件附件的程序,供楼主参考吧

Java code
import javax.mail.Authenticator;import javax.mail.Flags;import javax.mail.Folder;import javax.mail.Message;import javax.mail.Multipart;import javax.mail.Part;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.URLName;......public static Folder getMailFolder(String serverString, String username, String password) throws Exception {        Folder folder = null;               URLName server = new URLName(serverString);                session = Session.getInstance(new Properties(),                new MailAuthenticator(username, password));        folder = session.getFolder(server);                System.out.println("\n\n\nFolder retrieved for " + serverString + ", with " + folder.getMessageCount() + " messages");                return folder;    }    public static void getEmailWithSubjectContaining(String emailUrl,            String username, String password, String regex, String filepath,            boolean addPrefix, boolean delete) throws Exception {        Folder folder = getMailFolder(emailUrl, username, password);        if (folder == null)            return;        folder.open(Folder.READ_WRITE);        Message[] msgs = folder.getMessages();        System.out.println("Totally there are " + msgs.length);        for (int i = 0; i < msgs.length; i++) {            String pathToSave = filepath;                        String subject = msgs[i].getSubject();            System.out.println("Email subject: " + subject);            if (!subject.matches(regex)) {                System.out.println("Email subject doesn't match regex: " + regex + ", this email is ignored.");                continue;            }            Part p = (Part) msgs[i];            if (addPrefix) {                pathToSave = pathToSave + "/" + getFilenamePrefix(subject);            }            dumpAttachment(p, pathToSave);            msgs[i].setFlag(Flags.Flag.DELETED, delete);  //得到邮件后删除        }        folder.expunge(); //清除邮箱里DELETE的邮件        folder.close(false);    }    public static void dumpAttachment(Part part, String filepath) throws Exception{        if (part.isMimeType("text/plain")) {            System.out.println("This is plain text");        } else if (part.isMimeType("multipart/*")) {            System.out.println("This is a Multipart, trying to dig into the attachment now");            Multipart mp = (Multipart) part.getContent();            int count = mp.getCount();            for (int i = 0; i < count; i++)                dumpAttachment(mp.getBodyPart(i), filepath);        } else if (part.isMimeType("message/rfc822")) {            System.out.println("This is a Nested Message");            dumpAttachment((Part) part.getContent(), filepath);        } else {            Object o = part.getContent();            String attachmentFilename = "no_name";            if (part.getFileName() != null && !part.getFileName().equals("")) {                attachmentFilename = part.getFileName();            }                        if (o instanceof String) {                System.out.println("This is a string");            } else if (o instanceof InputStream) {                System.out.println("This is just an input stream");                InputStream is = (InputStream) o;                                FileOutputStream fos = new FileOutputStream(filepath + formatFileExtension(attachmentFilename));                int c;                int count = 0;                System.out.print("Saving attachment: " + formatFileExtension(attachmentFilename));                while ((c = is.read()) != -1) {                    fos.write(c);                    if (count % 1000000 == 0) {                        System.out.print("\n");                    } else if (count % 5000 == 0) {                        System.out.print(".");                    }                                        count ++;                }                System.out.println("\nAttachment " + (format.format((double)count/1024))  + " Kilobytes saved as '" + filepath + formatFileExtension(attachmentFilename) + "'\n");            } else {                System.out.println("This is an unknown type");                System.out.println(o.toString());            }        }    }......
  相关解决方案