If we are using .Net, we can easily access outlook and send emails using its own libraries.
But what if we are using Java?
Here we can seek the help of VBScripting to send the desired mail.
As a first step, we need to have a .vbs file created in our local. We will be modifying this .vbs file as needed to draft the changes we needed in our mail.
We can use PrintWriter method in Java to write into the vbs file.
Below given a sample of such a method. Here we have passed To Address, Mail Subject, Mail body, and path of the vbs file as the arguments.
We use these arguments to create an executable VBScript which on running will send the email from the currently logged-in Outlook session.
public static void sendOutlookMailFromCurrrentInstance(String strToAddress,String strSubject,String strBody,String strPath) throws Exception { String strPathTempExecuter =System.getProperty("java.io.tmpdir"); if (strPathTempExecuter.endsWith("\\")) strPathTempExecuter =strPathTempExecuter + "OutlookEmailDraft.vbs"; else strPathTempExecuter =strPathTempExecuter + "\\OutlookEmailDraft.vbs"; String[] strToList=strToAddress.split(";"); PrintWriter writer = new PrintWriter(strPathTempExecuter, "UTF-8"); writer.println("Set objOutlook = CreateObject(\"Outlook.Application\")"); writer.println("Set objMail = objOutlook.CreateItem(0)"); for(String strToID:strToList) { if(!strToID.isEmpty()) writer.println("objMail.Recipients.Add (\""+ strToID + "\")"); } writer.println("objMail.Subject = \"" + strSubject + "\""); writer.println("objMail.Body = \"" + strBody + "\""); writer.println("objMail.Attachments.Add(\""+ strPath + "\")"); writer.println("objMail.Send "); writer.println("Set objMail = Nothing"); writer.println("Set objOutlook = Nothing"); writer.close(); Runtime.getRuntime().exec("wscript \""+ strPathTempExecuter + "\""); }
//Executing VBScript Runtime.getRuntime().exec("wscript \""+ strPathTempExecuter + "\"");
No comments:
Post a Comment