September 15, 2022

How to send email from current Outlook instance using Java + VBScript

  September 15, 2022

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 + "\"");
}

The following line will execute the vbscript and sends the mail. 

//Executing VBScript
Runtime.getRuntime().exec("wscript \""+ strPathTempExecuter + "\"");

Since we are doing it outside of java, no exceptions will be shown in IDE if any error happens in the vbs file and the same goes for the delayed sending of mail.

To validate the mail sending status, we can write another vbs file to search the sent folder of outlook in the same manner with the mail subject as the attribute.
logoblog

Thanks for reading How to send email from current Outlook instance using Java + VBScript

Newest
You are reading the newest post

No comments:

Post a Comment

How to send email from current Outlook instance using Java + VBScript

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 ...