Attach files using selenium

Handling attach files with selenium alone is not possible. So lets use AutoIt for handling the task

AutoIt is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting.
First we will write a simple script in AutoIt and save the file as an executable (refer to post AutoIt-Save Script as executable)

Below is the sample AutoIt script:

WinWaitActive("Choose file")
Send("C:SeleniumSamplefile.txt") \location of the file you want to attach to the mail
Send("{ENTER}")

Now lets test it by adding an attachment to yahoo mail

main : This class is for starting selenium and launching the URL

public class main
{
public static DefaultSelenium ds;
public static void fn_launch(String br,String url)
{
ds=new DefaultSelenium("localhost",2233,br,url);
ds.start();
ds.windowMaximize();
ds.open("/");
}

}

attachfile_yahoomail : class to attach the file

public class attachfile_yahoomail extends main
{
public static void main(String[] args) throws Exception
{
fn_launch("http://www.yahoomail.com");
ds.type("login","id");
ds.type("passwd","password");
ds.click(".save");
Thread.sleep(5000);
ds.click("global_compose_top");
Thread.sleep(3000);
ds.type("to", "everythingabtselenium@gmail.com");
ds.type("Subj", "hello");
ds.type("compose_editorArea", "This is sample mail for testing attachments");
ds.click("attachFiles");
Thread.sleep(3000);
ds.getEval("window.document.getElementsByName('uploadfile')[0].click()");
Thread.sleep(3000);
Runtime.getRuntime().exec("E:\\selenium\\fileupload.exe");
/* Location of the autoit executable */
Thread.sleep(2000);
ds.click("attach_button_top");
while(ds.isVisible("to")==false)
{
Thread.sleep(2000);
}
ds.click("send_top");

 
}

}