Skip to Content

There are some requirements where you need to send file as an attachment to an Email with proper Email Body. Email attachment also should be named as required.

You will be wondering how to achieve this functionality with existing Email adapter options.Here I am providing the Generic Module code which renames the Email attachment with the file that you have attached in the File Adapter.

Below are the configurations that need to be done for achieving the functionality discussed.

File adapter Configurations:

Below are the configurations in the file adapter to attach the file which has to be attached in the mail Adapter.

fileadapterconfig.JPG

Make sure you check the ASMA parameters for File Name

fileASMA.JPG

I am using Mail package for customising the Email Body.

MailPackage.JPG

In this case, I am not parsing my input message. So some dummy input Message type is used and fields are mapped with constants.You can populate the fields of subject, From, To Fields with the required information. If you want these fields to be populated at Run time and required to change time to time, use parameterised Message Mapping.

For the Field Content_Type, populate text/plain;charset=”iso-8859-1″

contenttype.JPG

Coming to main part of interface is Mail Adapter configuration,

Mail Adapter Configurations:

As I am using Mail package, I have checked Use Mail Package option. File was attached in the file adapter which needs to be attached in the Email, so check Keep Attachments option in the adapter configurations.

Mailchannelconfig.JPG

Make sure that you have checked the ASMA Parameters in the Email Adapter.

MailASMA.JPG

Now try to process the your file as an attachment, You will see Email as below with untitled.xml as an attachment instead of file name that was attached.

untitiledmail.JPG

Now the question is how to change the attachment name as your input file name….Yes, it can be achieved. Please find the below module code for identifying your File attachment by the Mail adapter and rename the attachment with the file name.

Module Code:

/**

*

*/

package com.sap.emailattachment;

import java.rmi.RemoteException;

import java.util.StringTokenizer;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import javax.ejb.EJBException;

import javax.ejb.SessionBean;

import javax.ejb.SessionContext;

import javax.ejb.TimedObject;

import javax.ejb.Timer;

import com.sap.aii.af.lib.mp.module.Module;

import com.sap.aii.af.lib.mp.module.ModuleContext;

import com.sap.aii.af.lib.mp.module.ModuleData;

import com.sap.aii.af.lib.mp.module.ModuleException;

import com.sap.aii.af.service.auditlog.Audit;

import com.sap.engine.interfaces.messaging.api.Message;

import com.sap.engine.interfaces.messaging.api.MessageKey;

import com.sap.engine.interfaces.messaging.api.Payload;

import com.sap.engine.interfaces.messaging.api.PublicAPIAccessFactory;

import com.sap.engine.interfaces.messaging.api.XMLPayload;

import com.sap.engine.interfaces.messaging.api.auditlog.AuditAccess;

import com.sap.engine.interfaces.messaging.api.auditlog.AuditLogStatus;

import com.sap.tc.logging.Location;

/**

* @author Madhav.Poosarla

*

*/

public class EmailattachBean implements SessionBean, Module  {

public static final String VERSION_ID =”$Id://tc/aii/30_REL/src/_adapters/_sample/java/user/module/NGMINB_validateBean.java#1 $”;

           

            static final long serialVersionUID = 7435850550539048633L;

            String fileName = null;

            @SuppressWarnings(“deprecation”)

           

            public ModuleData process(ModuleContext moduleContext, ModuleData inputModuleData) throws ModuleException

            {

                        String SIGNATURE = “process(ModuleContext moduleContext, ModuleData inputModuleData)”;

                        Location location = null;

                        AuditAccess audit = null;

                        Payload attName =null;

                        int attnum=0;

                        try {

                                    location = Location.getLocation(this.getClass().getName());

                                    }

                        catch (Exception t)

                        {

                                    t.printStackTrace();

                                    ModuleException me = new ModuleException(“Unable to create trace location”, t);

                                    throw me;

                        }

                                    Object obj = null;

                                    Message msg = null;

                       

                        MessageKey key = null;

                        try {

                                   

                                    obj = inputModuleData.getPrincipalData();

                                    msg = (Message) obj;

                                    key = new MessageKey(msg.getMessageId(), msg.getMessageDirection());

                                    audit = PublicAPIAccessFactory.getPublicAPIAccess().getAuditAccess();// creating object for audit log

                                    audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, “EmailAttach: Module called”);

                       

                                    fileName = msg.getMessageProperty(“http://sap.com/xi/XI/System/File“, “FileName”);

                                   

                                    audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS,”RequestFileName:” + fileName);

                                    attnum=msg.countAttachments();

                                    audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS,”number of Attachment: ” + attnum);

                                    attName = msg.getAttachment(“%F”);

                                   

                                    msg.removeAttachment(“%F”);

                                    attnum=msg.countAttachments();

                                    if(attName != null)

                                    {

                                    audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS,”Name of Attachment: ” + attName.getName());

                                    }

                                                      else

                                    {

                                    audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS,”Attachment not found” + attName);

                                    }                   

                                    try

                                    {

                                                attName.setName(fileName);

                                                audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS,”Attachment name is successfully changed to : ” + attName.getName());

                                    }

                                    catch(Exception e)

                                    {

                                                audit.addAuditLogEntry(key, AuditLogStatus.ERROR,attName +”: attachmentName is not matching”);

                                                ModuleException me = new ModuleException(e);

                                                throw me;

                                    }        

                                  msg.addAttachment(attName);

                                               }

                                    catch (Exception e) {

                                    ModuleException me = new ModuleException(e);

                                    throw me; 

                                    }                      

                                    return inputModuleData;//sending original payload to call adapter.

        }

            /* (non-Javadoc)

             * @see javax.ejb.SessionBean#ejbActivate()

             */

            public void ejbActivate() throws EJBException, RemoteException {

                        // TODO Auto-generated method stub

            }

            /* (non-Javadoc)

             * @see javax.ejb.SessionBean#ejbPassivate()

             */

            public void ejbPassivate() throws EJBException, RemoteException {

                        // TODO Auto-generated method stub

            }

            /* (non-Javadoc)

             * @see javax.ejb.SessionBean#ejbRemove()

             */

            public void ejbRemove() throws EJBException, RemoteException {

                        // TODO Auto-generated method stub

            }

            /* (non-Javadoc)

             * @see javax.ejb.SessionBean#setSessionContext(javax.ejb.SessionContext)

             */

            public void setSessionContext(SessionContext arg0) throws EJBException,

                                    RemoteException {

                        // TODO Auto-generated method stub

            }

            /* (non-Javadoc)

             * @see javax.ejb.TimedObject#ejbTimeout(javax.ejb.Timer)

             */

            public void ejbTimeout(Timer arg0) {

                        // TODO Auto-generated method stub

            }

            public void ejbCreate() throws javax.ejb.CreateException {         

            }}

Below is the module configuration and make sure that you are Message Transformation bean with content disposition parameter.

Moduleparameter.JPG

I don’t want to send my mail body with single line as below.Once you deploy the Module, process the file as attachment. Here I am processing a PDF with the file name 2bg52000000.pdf

filePDF.JPG

Now Mail contains with the proper attachment of the file name that was sent.

Mailattachmentwithname.JPG

In this scenario, I wish to enhance one more functionality which is Email Body with which is customised. I don’t want to send my mail body with single line as below.

Mailattachmentwithbody.JPG

For customising your Email Body, it needs a small UDF while populating the data to the Content tag in the Mail package.

Graphicalmapping.JPG

In the Constant I am passing a String as below

**Automated Email-Dont Reply**,EmailBody,,ThankYou,Madhav

UDF nextLine which is used will identify the comma in the String and put it in the next line.

nextLine (UDF):

UDF.JPG

Now Email looks like as below!!!

final.JPG

To report this post you need to login first.

12 Comments

You must be Logged on to comment or reply to a post.

  1. Chitti Prakash

    Hi Madhav,

    It was really nice blog.

    I have another query related to attachments in Mail Adapter. If suppose I have special characters in the attachment name then, how PI Mail adapter will be able to handle them without changing into garbage character.

    How can we achieve this in Mail adapter? Do we need to write a custom module or do we have any standard modules available to achieve this?

    Thanks,

    Prakash.

    (0) 
  2. M. Igor

    Hi Gurus,

    i have a following scenario: XML to Mail as csv attachment.

    I have set up the scenario and it works if is use transform.content type as a static file name but when i try to rename it using FIleName from asma nothing happens eventhough the message monitoring says it change the name of the attachment.

    Can someone tell me what is wrong here and how can i fix it. I am on a PO 7.31 single stack

    Adapter Module Code:

    package com.sap.adaptermodule.rapportage;

    import java.util.Iterator;

    import java.util.Set;

    import javax.ejb.CreateException;

    import javax.ejb.SessionBean;

    import javax.ejb.SessionContext;

    import com.sap.aii.af.lib.mp.module.Module;

    import com.sap.aii.af.lib.mp.module.ModuleContext;

    import com.sap.aii.af.lib.mp.module.ModuleData;

    import com.sap.aii.af.lib.mp.module.ModuleException;

    import com.sap.engine.interfaces.messaging.api.Message;

    import com.sap.engine.interfaces.messaging.api.MessageKey;

    import com.sap.engine.interfaces.messaging.api.MessagePropertyKey;

    import com.sap.engine.interfaces.messaging.api.Payload;

    import com.sap.engine.interfaces.messaging.api.PublicAPIAccessFactory;

    import com.sap.engine.interfaces.messaging.api.auditlog.AuditAccess;

    import com.sap.engine.interfaces.messaging.api.auditlog.AuditLogStatus;

    import com.sap.tc.logging.Location;

    public class SetAttachmentNameBean implements SessionBean, Module {

        private SessionContext myContext;

        public void ejbRemove() {

        }

        public void ejbActivate() {

        }

        public void ejbPassivate() {

        }

        public void setSessionContext(SessionContext context) {

            myContext = context;

        }

        public void ejbCreate() throws CreateException {

        }

    public ModuleData process(ModuleContext moduleContext, ModuleData inputModuleData)

                          throws ModuleException{

      String SIGNATURE = “process(ModuleContext moduleContext, ModuleData inputModuleData)”;

      Location location = null;

      AuditAccess audit = null;

      MessageKey key = null;

      try {

        

      location = Location.getLocation(this.getClass().getName());

            Message msg = (Message) inputModuleData.getPrincipalData();

      key = new MessageKey(msg.getMessageId(), msg.getMessageDirection());

      audit = PublicAPIAccessFactory.getPublicAPIAccess()

      .getAuditAccess();// creating object for audit log

           

            Payload payload = msg.getDocument();

            Set<MessagePropertyKey> mpkSet = msg.getMessagePropertyKeys();

            Iterator<MessagePropertyKey> mpkIterator = mpkSet.iterator();

            MessagePropertyKey mpk = null;

            for (;mpkIterator.hasNext();){

            mpk = mpkIterator.next();

            audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, “Message Property gevonden met Name: ” + mpk.getPropertyName());

            if (“FileName”.equalsIgnoreCase(mpk.getPropertyName())){

            break;

            }

          

            }

           

            audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, “Payload gegevens initieel, Name: ” + payload.getName()+

            “, Description: ” + payload.getDescription() + “, ContentType: ” + payload.getContentType());

           

            String fileName = msg.getMessageProperty(new MessagePropertyKey(“FileName”, “http://sap.com/xi/XI/System/File“));

            if(fileName == null) fileName=”default.txt”;

     

            payload.setContentType(“text/plain;charset = \”UTF-8\”;” + “name=\”” + fileName + “\””);

         

           

            audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, “Payload gegevens na setten, Name: ” + payload.getName()+

            “, Description: ” + payload.getDescription() + “, ContentType: ” + payload.getContentType());

            inputModuleData.setPrincipalData(msg);

        } catch (Exception e) {

            throw new ModuleException(e);

        }

        return inputModuleData;

    }

    }

    This is my Mail adapter configuration:

    https://www.dropbox.com/s/7gp9n0fdwnxhf84/27-10-2014%209-15-53.jpg?dl=0

    https://www.dropbox.com/s/e2b2wi4uegfdflc/27-10-2014%209-16-29.jpg?dl=0

    https://www.dropbox.com/s/fj46pzkzsnkjc9x/27-10-2014%209-17-19.jpg?dl=0

    This is what message monitoring says:

    https://www.dropbox.com/s/vzz04n3i2fhaivr/27-10-2014%209-14-08.jpg?dl=0

    https://www.dropbox.com/s/9opsgz3dsny3uam/27-10-2014%209-30-25.jpg?dl=0

    https://www.dropbox.com/s/gtws1hgfr7f4l8b/27-10-2014%209-30-55.jpg?dl=0

    And this is my mail result

    https://www.dropbox.com/s/v0gh9my8eulzalm/27-10-2014%2010-08-47.jpg?dl=0

    I want the Attachment.xml to be renamed with ASMA FileName.

    (0) 
  3. Kir Hil

    Hello,

    I get this error in comm channel, when try to use this module:

    Delivery of the message to the application using connection Mail_http://sap.com/xi/XI/System failed, due to: com.sap.engine.interfaces.messaging.api.exception.MessagingException: java.lang.ClassCastException: Cannot cast class com.sun.proxy.$Proxy3408 to interface com.sap.aii.af.lib.mp.module.ModuleLocal


    Do you know what is the reason? this is my first implemented adapter…

    Pls help


    Thanks

    (0) 
  4. Brians Brown

    Hi,

    is very good this document….

    I have a question… I get file From FTP Directory and additional files option not exists…

    how must input the %F and other text?…. because I get errors on CC mail for null var for this problem…

    Thank experts!

    (0) 

Leave a Reply