Sending Email With Attachment In Rule

Which IIQ version are you inquiring about?

8.3

Share all details about your problem, including any error messages you may have received.

Hi,
I’m trying to send an email within a rule and attach a file that is being generated by that rule with the email. Is there anyway to do that?

import sailpoint.object.EmailTemplate;
import sailpoint.tools.EmailOptions;
import sailpoint.tools.EmailFileAttachment;
import sailpoint.tools.Util;
import sailpoint.tools.Message;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.File;

try {
    // Step 1: Generate the file
    String filePath = "C:\\IIQReports\\Report_" + simpleformat.format(cal.getTime()) + ".txt";
    Util.writeFile(filePath, sb.toString());

    // Step 2: Convert file to byte array
    byte[] fileData = Files.readAllBytes(Paths.get(filePath));
    String fileName = new File(filePath).getName();

    // Step 3: Create Email Template and Options
    EmailTemplate template = new EmailTemplate();
    EmailOptions options = new EmailOptions("[email protected]", null);

    // Set email content
    template.setBody("Please find the attached report.");
    template.setSubject("IIQ Report: " + simpleformat.format(cal.getTime()));

    // Step 4: Add file attachment
    EmailFileAttachment attachment = new EmailFileAttachment(fileName, EmailFileAttachment.MimeType.MIME_TEXT, fileData);
    options.addAttachment(attachment);

    // Step 5: Send the email
    context.sendEmailNotification(template, options);

    taskResult.addMessage(new Message(Message.Type.Info, "Email sent successfully with attachment.", null));
} catch (Exception e) {
    taskResult.addMessage(new Message(Message.Type.Error, "Error: " + e.getMessage(), null));
    return "Failure";
}

// Cleanup
context.decache();
return "Success";

This is what I’m using for that but I’m getting an error that EmailFileAttachment could not be found in the namespace.

Hi @Aaronlobo11

The MIME TYPE is not the right one. For TEXT Plain file, try using EmailFileAttachment.MimeType.MIME_PLAIN.

Hi,
I get the same error
It says EmailFileAttachment is not in the namespace

hi @Aaronlobo11

Please, use the following imports:

import sailpoint.object.EmailTemplate;
import sailpoint.object.EmailOptions;
import sailpoint.object.Attachment;
import sailpoint.service.AttachmentService;
import sailpoint.object.EmailFileAttachment;
import sailpoint.object.EmailFileAttachment.MimeType;
import sailpoint.object.EmailFileAttachment.*;
import sailpoint.object.ProvisioningPlan.*;
import sailpoint.service.AttachmentDTO;

Methods sailpoint.tools.* are wrongly set.

So to attach files, you can use following code:

<Script>
<Source>
import sailpoint.object.Identity;
import sailpoint.object.EmailTemplate;
import sailpoint.object.EmailOptions;
import sailpoint.object.Attachment;
import sailpoint.service.AttachmentService;
import sailpoint.object.EmailFileAttachment;
import sailpoint.object.EmailFileAttachment.MimeType;
import sailpoint.object.EmailFileAttachment.*;
import sailpoint.object.ProvisioningPlan.*;
import sailpoint.object.ProvisioningProject.*;
import sailpoint.service.AttachmentDTO;
import org.apache.log4j.Logger;
import sailpoint.integration.Base64;
import sailpoint.api.SailPointContext;
import java.nio.charset.StandardCharsets;

String supName = IdentityModel.get("supName");

Identity supervisor = context.getObjectById(Identity.class, supName);
String supervisorName = supervisor.getName();

EmailTemplate emailtemp = context.getObjectByName(EmailTemplate.class, "SET EMAIL TEMPLATE NAME HERE");
EmailOptions options = new EmailOptions();

options.setTo(supervisor.getEmail());
Attachment attached = context.getObjectById(Attachment.class, attachmentId);
byte[] pdfDecrypted = AttachmentService.decrypt(attached.getContent(), context);

 
EmailFileAttachment mailAttachment = new EmailFileAttachment(attached.getName() + ".pdf", MimeType.MIME_PDF, pdfDecrypted);


options.addAttachment(mailAttachment);

 

context.sendEmailNotification(emailtemp, options);
}
context.decache(emailtemp);
context.decache(supervisor);
return supervisorName;

</Source>
</Script>
1 Like

Thank you so much!
It worked

1 Like

I am using below to generate and report and need to sent email. I am able to generate report but unable to sent that csv attachemnt in email --------------------------

import java.net.HttpURLConnection;

import java.net.URL;

import java.io.OutputStream;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.Base64;

// API Configuration

String apiUrl = “http://myphone.caliberdirect.com/rest/v1/sailpoint/application”;

String userId = “sailpoint.tasks”;

String password = “y+B{i>;GOAMD!Ip6<0Tkb-”;

String jsonBody = “{” +

              "\"application\": {" +

              "\"name\": \"Newrez - Black Knight Process Management\"," +

              "\"operation\": \"Account Aggregation\"}" +

              "}";

try {

// Create Basic Authentication Header

String auth = userId + ":" + password;

String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());

String authHeader = "Basic " + encodedAuth;

// Create URL Connection

URL url = new URL(apiUrl);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("POST");

connection.setRequestProperty("Authorization", authHeader);

connection.setRequestProperty("Content-Type", "application/json");

connection.setDoOutput(true);

// Write JSON Body

try (OutputStream os = connection.getOutputStream()) {

    os.write(jsonBody.getBytes("UTF-8"));

    os.flush();

}

// Get Response Code

int responseCode = connection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) { // HTTP 200

    // Read Response

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    String inputLine;

    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {

        response.append(inputLine);

    }

    in.close();

    log.info("Response: " + response.toString());

} else {

    log.error("Request failed with HTTP Code: " + responseCode + ", Message: " + connection.getResponseMessage());

}

} catch (Exception e) {

log.error("An error occurred: " + e.getMessage(), e);

}



import java.net.HttpURLConnection;

import java.net.URL;

import java.io.OutputStream;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.Base64;

// API Configuration

String apiUrl = “http://myphone.caliberdirect.com/rest/v1/sailpoint/application”;

String userId = “sailpoint.tasks”;

String password = “y+B{i>;GOAMD!Ip6<0Tkb-”;

String jsonBody = “{” +

              "\"application\": {" +

              "\"name\": \"Newrez - Black Knight Process Management\"," +

              "\"operation\": \"Account Aggregation\"}" +

              "}";

try {

// Create Basic Authentication Header

String auth = userId + ":" + password;

String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());

String authHeader = "Basic " + encodedAuth;

// Create URL Connection

URL url = new URL(apiUrl);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("POST");

connection.setRequestProperty("Authorization", authHeader);

connection.setRequestProperty("Content-Type", "application/json");

connection.setDoOutput(true);

// Write JSON Body

try (OutputStream os = connection.getOutputStream()) {

    os.write(jsonBody.getBytes("UTF-8"));

    os.flush();

}

// Get Response Code

int responseCode = connection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) { // HTTP 200

    // Read Response

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    String inputLine;

    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {

        response.append(inputLine);

    }

    in.close();

    log.info("Response: " + response.toString());

} else {

    log.error("Request failed with HTTP Code: " + responseCode + ", Message: " + connection.getResponseMessage());

}

} catch (Exception e) {

log.error("An error occurred: " + e.getMessage(), e);

}

working code -----------------------import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.entity.StringEntity;

import org.apache.http.util.EntityUtils;

// API Configuration

String apiUrl = “http://myphone.caliberdirect.com/rest/v1/sailpoint/application”;

String userId = “sailpoint.tasks”;

String password = “y+B{i>;GOAMD!Ip6<0Tkb-”;

String jsonBody = “{"application": {"name": "Newrez - Black Knight Process Management", "operation": "Test Connection"}}”;

try {

// Create HTTP Client

CloseableHttpClient httpClient = HttpClients.createDefault();

// Create HTTP Post Request

HttpPost post = new HttpPost(apiUrl);

// Set Headers

String auth = Base64.getEncoder().encodeToString((userId + ":" + password).getBytes());

post.setHeader("Authorization", "Basic " + auth);

post.setHeader("Content-Type", "application/json");

// Set JSON Body

StringEntity entity = new StringEntity(jsonBody);

post.setEntity(entity);

//return “Test” ;

// Execute Request

CloseableHttpResponse response = httpClient.execute(post);

// Process Response

int statusCode = response.getStatusLine().getStatusCode();

if (statusCode == 200) {

    String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");

    log.info("Response: " + responseBody);

} else {

    log.error("Request failed with HTTP Code: " + statusCode + ", Message: " + response.getStatusLine().getReasonPhrase());

}

// Close Response

response.close();

} catch (Exception e) {

log.error("An error occurred: " + e.getMessage(), e);

}


a00185a

{

“application”: {

“name”: “Newrez - Black Knight Process Management”,

“operation”: “Test Connection”

}

}

GET http://myphone.caliberdirect.com/rest/v1/sailpoint/application

<?xml version='1.0' encoding='UTF-8'?> We use this rule to check if is active and has any of profie listed in custom objects.

import java.util.Map;

import sailpoint.object.Identity;

import sailpoint.object.QueryOptions;

import sailpoint.object.Filter;

import java.util.Date;

import java.text.SimpleDateFormat;

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

import net.schmizz.sshj.SSHClient;

import net.schmizz.sshj.sftp.SFTPClient;

import net.schmizz.sshj.xfer.FileSystemFile;

import net.schmizz.sshj.transport.verification.PromiscuousVerifier;

import org.apache.log4j.Level;

import org.apache.log4j.Logger;

import sailpoint.object.*;

import com.didisoft.pgp.*;

import java.io.*;

	private static Logger log = Logger.getLogger("syngenta.wand.rules");

	StringBuffer buffer = new StringBuffer();

	PGPLib pgp = new PGPLib();

	boolean createfileStatus = false;

	log.debug("this is ReverseSync file Upload Report");

	public boolean execute(Identity identity) throws Exception {

	// Get the created date of the identity

	Date created = identity.getCreated();

	// Get the current date

	Date today = new Date();

	// Compare the dates by ignoring the time part

	boolean isToday = (created.getYear() == today.getYear()) @and (created.getMonth() == today.getMonth()) @and (created.getDate() == today.getDate());

	// Return the boolean value

	log.debug("isToday"+isToday);

	return isToday;

	}

	QueryOptions op = new QueryOptions();

	Filter[] filters = new Filter[1];

	List filterList = new ArrayList();

	filterList.add(Filter.eq("links.application.name", "WAND File Ingestion"));

	filters[0] = Filter.and(filterList);

	op.add(filters);

	List identities = context.getObjects(Identity.class, op); 

	buffer.append("Worker ID|SID|Syngenta Email").append("\n");

	for(Identity identity: identities){

	if(execute(identity)){

	log.debug("Iterating through idenitity");

	String workerID = identity.getAttribute("personSubGroup")!=null? identity.getAttribute("personSubGroup").split("-")[1]:"";

	if(null!=workerID &amp;&amp;workerID.contains(","))

	workerID = "\"" +workerID+"\"";

	String sid = identity.getName()!=null? identity.getName():"";

	if(null!=sid &amp;&amp;sid.contains(","))

	sid = "\"" +sid+"\"";

	String emailAddress = identity.getAttribute("email")!=null? identity.getAttribute("email"):"";

	if(null!=emailAddress &amp;&amp;emailAddress.contains(","))

	emailAddress = "\"" +emailAddress+"\"";

	buffer.append(workerID+"|"+sid+"|"+emailAddress).append("\n");

	createfileStatus = true;

	context.decache(identity);

	}

	}

	log.debug("Creating reverse sync report");

	if(createfileStatus){

	DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

	LocalDateTime localDate = LocalDateTime.now();

	String timeStamp = localDate.format(dateFormat);

	//System.out.println("Wand - customization Rules::timeStamp:: "+timeStamp);

	timeStamp = "-" + timeStamp.replaceAll("[^a-zA-Z0-9\\.\\-]", "_");

	//System.out.println("Wand - customization Rules::timeStamp "+timeStamp);

	String directory = "/sailpoint/outbound/";

	String filepath = "//IEAZIWAPPD027//syngenta.wand//Wand//WandReverseSync"+timeStamp+".csv";

	String remote = "//IEAZIWAPPD027//syngenta.wand//Wand//WandReverseSyncEncrypt"+timeStamp+".csv";

	//String CSV_FILE_PATH = "E://Wand//WandReverseSync"+timeStamp+".csv";

	File file = new File(filepath);

	file.createNewFile();

	FileWriter fw = new FileWriter(file, true);

	BufferedWriter bw = new BufferedWriter(fw);

	bw.write(buffer.toString());

	bw.close();

	String publikKeyFilePath = "//IEAZIWAPPD027//syngenta.wand//Keys//PRO-Unlimited-Key-2K-public - PGP key with 2K strength.asc";

    boolean asciiArmor = false;

    // if true additional integrity check information is added

    // set to false for compatibility with older versions of PGP such as 6.5.8.

    boolean withIntegrityCheck = false;

    pgp.encryptFile(filepath,

    				publikKeyFilePath,

    				remote,

    				asciiArmor, 

    				withIntegrityCheck);

	SSHClient sshClient = new SSHClient();

	sshClient.addHostKeyVerifier(new PromiscuousVerifier());

	sshClient.setConnectTimeout(1000);

	sshClient.connect("sftp-global.syngenta.com", 22);

	sshClient.authPassword("wand_prod", "WaNdTPr0DrH#49Qw1");

	log.debug("Inside Connection");

	Boolean Result = sshClient.isAuthenticated();

   // System.out.println(Result);

	log.debug("Result: " +result);

	SFTPClient sftpClient = sshClient.newSFTPClient();

	sftpClient.put(new FileSystemFile(remote), directory);

	}

	log.debug("Reverse Sync File Uploaded succussfully");

hi


<?xml version='1.0' encoding='UTF-8'?> Debugging Tool - Sends a sample email out via the email server.
      The log object associated with the SailPointContext.
      A sailpoint.api.SailPointContext object that can be used to query the database if necessary.
   // Library inclusions for BeanShell

import sailpoint.api.*;

import sailpoint.object.*;

import sailpoint.tools.*;

import java.util.*;

import java.lang.*;

import java.text.*;

// Point this to the “To” email address

String emailDest = “[email protected]”;

// Specify the email template name in tplName

String tplName = “SailPoint - Test Email Sending”;

EmailTemplate template = context.getObjectByName(EmailTemplate.class, tplName);

if (null == template) {

log.error("ERROR: could not find email template [ " + tplName + “]”);

return;

}

template = (EmailTemplate) template.deepCopy(context);

if (null == template) {

log.error("ERROR: failed to deepCopy template [ " + tplName + “]”);

return;

}

Map args = new HashMap();

// Add all args needed by the template like this

args.put(“testField1”, “This is a test of template parameters.”);

EmailOptions ops = new EmailOptions(emailDest, args);

context.sendEmailNotification(template, ops);

return;


import sailpoint.object.EmailTemplate;import sailpoint.tools.EmailOptions;import sailpoint.tools.EmailFileAttachment;import sailpoint.tools.Util;import sailpoint.tools.Message; import java.nio.file.Files;import java.nio.file.Paths;import java.io.File; try { // Step 1: Generate the fileString filePath = “C:\IIQReports\Report_” + simpleformat.format(cal.getTime()) + “.txt”;
Util.writeFile(filePath, sb.toString());
// Step 2: Convert file to byte array
byte fileData = Files.readAllBytes(Paths.get(filePath));
String fileName = new File(filePath).getName();
// Step 3: Create Email Template and Options
EmailTemplate template = new EmailTemplate();
EmailOptions options = new EmailOptions(“[email protected]”, null);
// Set email content
template.setBody(“Please find the attached report.”);
template.setSubject("IIQ Report: " + simpleformat.format(cal.getTime()));
// Step 4: Add file attachment
EmailFileAttachment attachment = new EmailFileAttachment(fileName, EmailFileAttachment.MimeType.MIME_TEXT, fileData);
options.addAttachment(attachment);
// Step 5: Send the email
context.sendEmailNotification(template, options);
taskResult.addMessage(new Message(Message.Type.Info, “Email sent successfully with attachment.”, null));} catch (Exception e) { taskResult.addMessage(new Message(Message.Type.Error, "Error: " + e.getMessage(), null)); return “Failure”; } // Cleanupcontext.decache();return “Success”;


import java.io.FileWriter;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Iterator;

import sailpoint.object.Identity;

import sailpoint.api.SailPointContext;

import sailpoint.object.Filter;

import sailpoint.object.QueryOptions;

import sailpoint.object.EmailTemplate;

import sailpoint.tools.EmailOptions;

import sailpoint.tools.EmailFileAttachment;

import sailpoint.tools.Util;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.io.File;

public String generateAndEmailReport(SailPointContext context) {

try {

    // Step 1: Define output file path

    String directoryPath = "C:/Terminated";

  return"directoryPath";

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");

    String timestamp = sdf.format(new Date());

    // Generate file path with timestamp

    String filePath = directoryPath + "/users_terminated_" + timestamp + ".csv";

    // Ensure directory exists

    File dir = new File(directoryPath);

    if (!dir.exists()) {

        dir.mkdirs();

    }

    // Step 2: Generate the CSV file

    PrintWriter writer = new PrintWriter(new FileWriter(filePath));

    writer.println("hrStatus,terminationDate,email,employeeId,name,firstname,lastname");

    // Get today's date in the desired format

    SimpleDateFormat dateOnlyFormat = new SimpleDateFormat("MM/dd/yyyy");

    String todayDate = dateOnlyFormat.format(new Date());

    // Build query options for terminated contractors

    QueryOptions queryOptions = new QueryOptions();

    queryOptions.addFilter(Filter.eq("type", "Contractor")); // Assuming `type` identifies contractors

    queryOptions.addFilter(Filter.eq("hrStatus", "Terminated"));

    // Retrieve identities using an Iterator

    Iterator iterator = context.search(Identity.class, queryOptions);

    // Iterate over identities and write to CSV if termination date matches today's date

    while (iterator.hasNext()) {

        Identity identity = (Identity) iterator.next();

        String hrStatus = identity.getAttribute("hrStatus") != null ? identity.getAttribute("hrStatus").toString() : "";

        String terminationDate = identity.getAttribute("terminationDate") != null ? identity.getAttribute("terminationDate").toString() : "";

        String email = identity.getAttribute("email") != null ? identity.getAttribute("email").toString() : "";

        String employeeId = identity.getAttribute("employeeId") != null ? identity.getAttribute("employeeId").toString() : "";

        String firstname = identity.getAttribute("firstname") != null ? identity.getAttribute("firstname").toString() : "";

        String lastname = identity.getAttribute("lastname") != null ? identity.getAttribute("lastname").toString() : "";

        String name = identity.getName() != null ? identity.getName() : "";

        // Only include users terminated today

        if (terminationDate.equals(todayDate)) {

            writer.println(hrStatus + "," + terminationDate + "," + email + "," + employeeId + "," + name + "," + firstname + "," + lastname);

        }

    }

    writer.close();

    log.info("CSV report generated successfully: " + filePath);

  

    // Step 3: Convert the file to a byte array

    byte[] fileData = Files.readAllBytes(Paths.get(filePath));

    String fileName = new File(filePath).getName();

    // Step 4: Create email template and options

    EmailTemplate template = new EmailTemplate();

    EmailOptions options = new EmailOptions("[email protected]", null);

    // Set email content

    template.setBody("Please find the attached report of terminated contractors.");

    template.setSubject("Daily Terminated Contractors Report: " + dateOnlyFormat.format(new Date()));

    // Step 5: Add the file attachment

    EmailFileAttachment attachment = new EmailFileAttachment(fileName, EmailFileAttachment.MimeType.MIME_CSV, fileData);

    options.addAttachment(attachment);

    // Step 6: Send the email

    context.sendEmailNotification(template, options);

    log.info("Email sent successfully with attachment.");

  //  return "Success";

} catch (Exception e) {

    log.error("Error generating or emailing the report: " + e.getMessage(), e);

   // return "Failure";

} finally {

    context.decache();

}

}

Any help

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.