Skip to Content
avatar image
Former Member

Java Mapping - E-mail with xml attachment and body text .

Hi experts.

I have a scenario where i need to send the NFE XML in the mail attachment and a text in the mail body. The standard solution using a message type with fields of the NFE XML both for receiver and sending message, so it was necessary to create JAVA MAPPING using a structure XI MAIL: SAP Note 748024.

Follow the JAVA MAPPING used:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
import com.sap.aii.mapping.api.StreamTransformation;
import com.sap.aii.mapping.api.StreamTransformationException;
import com.sap.aii.mapping.lookup.Channel;
import com.sap.aii.mapping.lookup.LookupService;
import com.sap.aii.mapping.lookup.RfcAccessor;
import com.sap.aii.mapping.lookup.XmlPayload;
public class XmlNFe_To_Mail implements StreamTransformation{
    private String prefixoSubject = new String();
    private String emailFrom = new String();
    private String prefixoDocumento = new String();
    private String frase = new String();
    private String gap = "\n\r";
    private final String NFe = "NFE";
    public String getGap() {
        return gap;
    }
    public void setGap(String gap) {
        this.gap = gap;
    }
    public String getFrase() {
        return frase;
    }
    public void setFrase(String frase) {
        this.frase = frase;
    }
    //INI-------------------------------------------------------------
    static String BSystem = "SAP_ERP_QAS_500";
    static String CChannel = "WAS_RFC_RCV";
    public String getBSystem() {
        return BSystem;
    }
    public String getPrefixoSubject() {
        return prefixoSubject;
    }
    public void setPrefixoSubject(String prefixoSubject) {
        this.prefixoSubject = prefixoSubject;
    }
    public String getEmailFrom() {
        return emailFrom;
    }
    public void setEmailFrom(String emailFrom) {
        this.emailFrom = emailFrom;
    }
    public String getPrefixoDocumento() {
        return prefixoDocumento;
    }
    public void setPrefixoDocumento(String prefixoDocumento) {
        this.prefixoDocumento = prefixoDocumento;
    }
    public String getCChannel() {
        return CChannel;
    }
    private void configParamEmail(){
        setEmailFrom("fiscal@netshoes.com");
        setPrefixoDocumento(NFe);
        setPrefixoSubject(NFe);
    }
    public void execute(InputStream in, OutputStream out)
            throws StreamTransformationException {
        try{
            configParamEmail();
            //Transforma mensagem em entrada em string ----INICIO
            BufferedReader inpxml = new BufferedReader(new InputStreamReader(in));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = inpxml.readLine()) != null) {
                buffer.append(line);
            }
            String inptxml = buffer.toString();
            //Obtendo dados para o envio de e-mail
            String idNFe = "";
            String numeroNF = "";
            idNFe = inptxml.substring(inptxml.indexOf("<chNFe>")+7,inptxml.indexOf("</chNFe>"));
            numeroNF = idNFe.substring(25,34);
            if ( inptxml.indexOf("infEvento") > 0){
                this.setPrefixoDocumento(this.getPrefixoDocumento().replaceAll("NFE", "CCE"));
                this.setPrefixoSubject(this.getPrefixoSubject().replaceAll("NFE ", "CCE"));
            }
            if ( inptxml.indexOf("infCanc") > 0){
                this.setPrefixoDocumento(this.getPrefixoDocumento().replaceAll("NFE", "CancNFe "));
                this.setPrefixoSubject(this.getPrefixoSubject().replaceAll("NFE ", "NFE CANCELADA"));
            }
            //--------------------- RFC LOOKUP -----------------------------------------
            Channel chn = null;
            RfcAccessor rfc = null;
            String email = "";
            chn = LookupService.getChannel(this.getBSystem(), this.getCChannel());
            rfc = LookupService.getRfcAccessor(chn);
            String req = "<ns0:ZFSD017 xmlns:ns0='urn:sap-com:document:sap:rfc:functions'><ZACCKEY>" 
            + idNFe 
            + "</ZACCKEY></ns0:ZFSD017>";
            InputStream inputRFC = new ByteArrayInputStream(req.getBytes("UTF-8"));
            XmlPayload rfcPayload = LookupService.getXmlPayload(inputRFC);
            XmlPayload result = rfc.call(rfcPayload);
            InputStream resp = result.getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(resp);
            Node node = (Node) doc.getElementsByTagName("EMAIL_CLI").item(0);
            if (node.hasChildNodes() && !node.getFirstChild().getNodeValue().equals("")) {
                email = node.getFirstChild().getNodeValue();
            }
            //monta XML de saida XiMail
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transform = tf.newTransformer();
            //Cria escopo do XML
            Document docout = db.newDocument();
            Element root = docout.createElement("ns1:Mail");
            root.setAttribute("xmlns:ns1", "http://sap.com/xi/XI/Mail/30");
            docout.appendChild(root);
            //Cria elemento Subject
            Element subject = docout.createElement("Subject");
            root.appendChild(subject);
            Text subjectText = docout.createTextNode(getPrefixoSubject()+numeroNF); //Cria valor campo
            subject.appendChild(subjectText);
            //Cria elemento From
            Element from = docout.createElement("From");
            root.appendChild(from);
            Text fromText = docout.createTextNode(getEmailFrom()); //Cria valor campo
            from.appendChild(fromText);
            if ( email.length() > 0 ){
                email += ";";
            }else {
                email = "fiscal@netshoes.com";
            }
            //Cria elemento To
            Element to = docout.createElement("To");
            root.appendChild(to);
            Text toText = docout.createTextNode(email); //Cria valor campo
            to.appendChild(toText);
            //Cria elemento Content Type
            Element contentType = docout.createElement("Content_Type");
            root.appendChild(contentType);
            Text contentTypeText = docout.createTextNode("multipart/mixed;boundary=--AaZz"); //Cria valor campo
            contentType.appendChild(contentTypeText);
            // Criando o corpo de texto do e-mail e o anexo
            Element content = docout.createElement("Content");
            root.appendChild(content);          
            String bodyText = "";
            StringBuilder finalBodyText = new StringBuilder();
            Text contentText;
            node = (Node) doc.getElementsByTagName("BODY_TEXT").item(0);
            if (node.hasChildNodes() && !node.getFirstChild().getNodeValue().equals("")) {
            bodyText = node.getFirstChild().getNodeValue();
                finalBodyText.append("----AaZz\r\n Content-Type: text/plain; charset=UTF-8\r\n")
                             .append("Content-Disposition: inline\r\n\r\n")
                             .append(bodyText)
                             .append("\r\n----AaZz\r\nContent-Disposition: attachment; filename= NFE: ")
                             .append(idNFe)
                             .append(".xml")
                             .append("\r\n\r\n")
                             .append(inptxml.replaceAll("\n", ""))
                             .append("\r\n");
            }                                  
            contentText = (docout.createTextNode(finalBodyText.toString()));
            content.appendChild(contentText);            
            //Fecha o XML
            DOMSource domS = new DOMSource(docout);
            transform.transform((domS), new StreamResult(out));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void setParameter(Map arg0) {
        // TODO Auto-generated method stub
    }
}

Mail arrives with body text and attachment XML, but attachment XML comes broken, as if it had broken line, and with that error at the time to reading XML

I would like your help in resolving this problem.

xml-broken.png (148.4 kB)
Add comment
10|10000 characters needed characters exceeded

  • Get RSS Feed

2 Answers

  • Best Answer
    Sep 07, 2017 at 07:14 PM

    Hello,

    I think you would have a higher probability of getting a response from NW PI experts, so I'd recommend you to change the tags of your posting to reflect it.

    Regards,

    Renan Correa

    Add comment
    10|10000 characters needed characters exceeded

  • avatar image
    Former Member
    Oct 27, 2017 at 10:24 PM

    Oi,

    Reconheco esse codigo ehehe...

    Conseguiu resolver ?

    Acredito que seja do XML esse problema e não leitura e conversatio bit a bit do arquivo.

    Add comment
    10|10000 characters needed characters exceeded