get the attachment files of an email

29 Jul '15, 01:27 AM
36,074 Views

Hello, I want to create a simple web application that the user sets his email addres, password and then, the application shows his inbox and the user selects an email and the application gets the attachments files to save in the hard disk.

I don´t want to get the script released, but I would get some clues

 
x 0
Follow
Answer Answer at this question and get points!
Forum Starter - Level 2

Hi,

 

Working with JavaMail is not an easy thing. First of all, you must know how the files are stored inside of an email. For this, I would recommend to read the JavaMail API (https://javamail.java.net/nonav/docs/api/). Furthermore, I managed to read attachments from Webratio using a script unit with the following source:

#input String host, String port, String username, String password, String defaultFrom, String titluMesaj
#output body, attachment_name, sender, senderEmail, emailDate, subjectEmail
import com.webratio.rtx.core.BeanHelper
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.sql.*;
//import com.sun.mail.pop3.*;
import com.sun.mail.imap.*;

import org.apache.commons.lang.StringUtils;
import com.webratio.rtx.RTXBLOBData;
import com.webratio.rtx.blob.BLOBData;
import com.webratio.rtx.RTXBLOBService;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import com.webratio.rtx.blob.ExternalBLOBData
import com.webratio.rtx.blob.ByteArrayBLOBData
import java.text.DateFormat
import java.text.Format
import java.text.SimpleDateFormat;
import java.util.*;

println "========================================"
println "Host: [" +  host+"]"
println "Port: ["+port+"]"
println "Mail username: [" +username+"]"
println "Mail password: [" + password+"]"
println "DefaultFrom: [" + defaultFrom+"]"
println "Titlu: ["+titluMesaj+"]"
println "========================================"

CounterHelper.x = 0

public class CounterHelper {
    public static int x = 0
    public static int increaseCounter(int x)
    {
        CounterHelper.x++

        return CounterHelper.x
    }
}


    body = []
    atasament =[]
    attachment_name =[]
    sender = []
    senderEmail = []
    emailDate =[]
    subjectEmail =[]

    uploadDir = rtx.getUploadDirectory();


            Folder folder = null;
            def store = null;
            String mailPop3Host = host;
            String mailPop3Port = port;
            String mailStoreType = "imap";
            String mailUser = username;
            String mailPassword = password;
        
        
            try {
                Properties props = System.getProperties();
                //Setting JavaMail Properties
                props.setProperty("mail.store.protocol", "imap");
                props.setProperty("mail.imap.auth.plain.disable", "true");
                props.setProperty("mail.imap.auth.ntlm.disable", "true");    
                props.setProperty("mail.imap.auth.gssapi.disable", "true");
                props.setProperty("mail.imap.ssl.enable", "false");
                props.setProperty("mail.imap.host", host);
                props.setProperty("mail.imap.port", port);
            
                Session session = Session.getDefaultInstance(props, null);
                //Debugging java.mail
                session.setDebug(true);
                store =  session.getStore(mailStoreType);
                store.connect(username, password);
                folder = store.getFolder("Inbox");
        
        
                folder.open(Folder.READ_WRITE);
                def messages = folder.getMessages();
                System.out.println("No of Messages : " + folder.getMessageCount());
                System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
                
                for (int i=0; i < messages.length; ++i) {
                    
                    Message msg = messages[i];
                    
                    //This will look only for unread emails

                    if (!msg.isSet(Flags.Flag.SEEN)) {
                       
                        // Location of saved attachment
                        String filename = "";
                        recursiveGetContent(msg.getContent(), filename);
                        
                    //To mark parsed emails as read it will use msg.setFlag(Flags.Flag.SEEN, true); otherwise msg.setFlag(Flags.Flag.SEEN, false);
                       msg.setFlag(Flags.Flag.SEEN, true);
                        
        
                    }
                }
            }
            catch(Exception e)
            {
            e.printStackTrace();
            }
            finally {
                if (folder != null) { folder.close(true); }
                if (store != null) { store.close(); }
                

            }
        

def recursiveGetContent(Object content, String filename)
        throws IOException, MessagingException
    {
    
        OutputStream out = null;
        InputStream inpStream;
        try {
            if (content instanceof Multipart) {
                Multipart multi = ((Multipart)content);
                int parts = multi.getCount();
                for (int j=0; j < parts; ++j) {
                    MimeBodyPart part = (MimeBodyPart)multi.getBodyPart(j);
                    if (part.getContent() instanceof Multipart) {
                        
                        recursiveGetContent(part.getContent(), filename);
                    }
                    else {
                        String extension = "";
                        if (part.isMimeType("text/html")) {
                            extension = "html";
                        }
                        else {
                            if (part.isMimeType("text/plain")) {
                                extension = "txt";
                                try{
                                    BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream()));
    
                                    StringBuilder iesire = new StringBuilder();
                                    String line;
                                    while ((line = reader.readLine()) != null) {
                                        iesire.append(line);
                                    }
                                   
                                    body[CounterHelper.x]=iesire.toString()
    
                                    reader.close();}
                                catch (Exception ex) {println ex.printStackTrace()}
                            }
                            else {
                                //  Name of atachment
                                extension = part.getDataHandler().getName();
                                filename = filename+ extension;
                                attachment_name[CounterHelper.x]=uploadDir+File.separator+extension;
                              
                                out = new FileOutputStream(new File(uploadDir+File.separator+filename));
                                inpStream = part.getInputStream();
                                int k;
                                while ((k = inpStream.read()) != -1) {
                                    out.write(k);
                                }
                             
                                
                                
                            }
    
                        }
                    }
                }
            }
        }
        catch(Exception e){
                println e.printStackTrace()
        }
        finally {
            if (inpStream != null) { inpStream.close(); }
            if (out != null) { out.flush(); out.close(); }
            
        }
    }
body, attachment_out, attachment_name, sender, senderEmail, emailDate, subjectEmail
    
return [ 
        "attachment_name": (String[]) attachment_name,
        "body": (String[]) body,
        "sender":  (String[]) sender,
        "senderEmail":  (String[]) senderEmail,
        "emailDate":  (String[]) emailDate,
        "subjectEmail":  (String[]) subjectEmail
        ]

 

 

After this, I obtained an array of filepaths (attachment_name) which was passed in a loop unit in order to obtain an array of files (this could have been done in the same script but I've chosen this because I had to create a specific business flow). So, the script to get the files inside of an array is the following:

 

 

#input String filePath
#output blobFile, fileName
import com.webratio.rtx.core.BeanHelper

import com.webratio.rtx.RTXBLOBData
import com.webratio.rtx.blob.BLOBData
import com.webratio.rtx.blob.ExternalBLOBData
import com.webratio.rtx.blob.ByteArrayBLOBData
import org.apache.commons.lang.StringUtils
import java.io.File


println filePath
def path = StringUtils.substringBeforeLast(filePath, "\\")
def fileName = StringUtils.substringAfterLast(filePath, "\\")
def ext = StringUtils.substringAfterLast(filePath, ".")
java.io.File inputFile = new java.io.File(path, fileName);
RTXBLOBData blobFile = new ExternalBLOBData(fileName, inputFile, rtx);


return ["blobFile": blobFile, "fileName": fileName]

 

Hope this will be helpful

   
x 1
No Forum Badges

The first thing you need is to configure your SMTP server on WebRatio.
After you set the "Acction" in loop mode.

I hope I helped you.

 
x 0

I got this code, http://www.codejava.net/java-ee/javamail/download-attachments-in-e-mail-messages-using-javamail

but when I run it in eclipse platform, it don't show anything and the console is making some opperations

if I run the script in WebRatio, it generates the page, but in Tomcat console apears the following message: 

http://1drv.ms/1Ismhhd

 
x 0
Answer at this question and get points!

Related questions

Acceder a diferentes site views/ Acces to diferents site views Add to Bag link in ACME any webratio book ? Asking For a Book Attribute comparison in a selector unit Clarification about the NoOperation unit Codigo QR Como hacer un menu en webratio? Conditional Expression "greater than 0" on null fields Connect more query unit Content module page variable won't assign. coupled mandatory fields Create Unit with Date (Year only) Custom Attributes Condition Database Database List is not showing up in App Emulator Data is always created doubled Data Management: Updating Data - Attachments - Updating Data Sample Project Final Description: Unknown tag 'wr:LinkResource' Dudas sobre modelado(Data Flow,Forms y Operation Create) Empty record mistakenly saved en_US codify problem Export XML external link.= Filter information in a Simple List Format currency forward/backward navigation and bookmark in ajax web app "Generation Error" with Generate and Run Generation options problem Get Unit problem Get Year from Date Help for connect public and private site views How can i create pagemenu or landmarkmenu with multiple levels. How does WebRatio represent these IFML elements? / ¿Cómo representa WebRatio estos elementos IFML? How i can reuse modules in multiple projects? How to define the sequence of execution units on a page? How to display the attributes of a related entity. How to filter imported attributes? How to include Selector Unit result in Mail Unit Body? How to pass vars to a alternative page How to process IFML Model (build with Eclipse editor) with ATL How to show a page based on a boolean? How to speed up the "last" link using PowerIndexUnit for lots of records How to store data related to an entity in relationships in a project web Insert data into database Insert master page to many hybrid modules Integrating a BPM model into an existent WebML model JSON I/O Unit e informazioni derivate KO Links in Selector Unit Landmark in hybrid module Link localization Links from Index unit with condition Link Visibility Condition Power Index Unit Mail multipla maintain the record order in a sortable list Math Unit to update attributes of an entity? [MOBILE] How I extract information from JSON client side? Modifica Entità tramite file xml Multi Entry Unit: How to forward only checked rows? multi-lingual product description Non riesco a fare funzionare Xml out unit Parametrizzazione Selector Unit Problem Example create Unit (no company in employee table) Problem in adding diagrams in IFML Editor (Eclipse) Problem with query unit! Problem with Scroller Unit query a database Question about Site Views Rename passing attributes Replace ID by its value in another table Search by Selector component does not work Select between parameters Selector unit doesn't return any value in hybrid module Sending mails is not working Sending mails with gmail is not working Setting the Default link for a Switch unit show/hide fields on button click (registration page) [solved] all links transparent, why ? Something leads to wrong condition expression evaluation. sumar atributos de una tabla filtrado por Role Condition Sum entity's values Transportation Link issue Unique Fields using relationship role conditional with null usuarios y grupos utilizzo componenti database Visibility Condition on Multiple Links From Index Unit WebRation - Create Navigation diagram